@shopify/hydrogen-react
Version:
React components, hooks, and utilities for creating custom Shopify storefronts
1 lines • 2.02 kB
Source Map (JSON)
{"version":3,"file":"useSelectedOptionInUrlParam.mjs","sources":["../../src/useSelectedOptionInUrlParam.tsx"],"sourcesContent":["import {useEffect} from 'react';\nimport {mapSelectedProductOptionToObject} from './getProductOptions.js';\nimport {SelectedOption} from './storefront-api-types.js';\n\nexport function useSelectedOptionInUrlParam(\n selectedOptions: Pick<SelectedOption, 'name' | 'value'>[],\n): null {\n useEffect(() => {\n const optionsSearchParams = new URLSearchParams(\n mapSelectedProductOptionToObject(selectedOptions || []),\n );\n const currentSearchParams = new URLSearchParams(window.location.search);\n\n // ts ignoring the URLSearchParams not iterable error for now\n // https://stackoverflow.com/questions/72522489/urlsearchparams-not-accepting-string#answer-72522838\n // TODO: update ts lib\n const combinedSearchParams = new URLSearchParams({\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n ...Object.fromEntries(currentSearchParams),\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n ...Object.fromEntries(optionsSearchParams),\n });\n\n if (combinedSearchParams.size > 0) {\n window.history.replaceState(\n {},\n '',\n `${window.location.pathname}?${combinedSearchParams.toString()}`,\n );\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [JSON.stringify(selectedOptions)]);\n\n return null;\n}\n"],"names":[],"mappings":";;AAIO,SAAS,4BACd,iBACM;AACN,YAAU,MAAM;AACd,UAAM,sBAAsB,IAAI;AAAA,MAC9B,iCAAiC,mBAAmB,CAAA,CAAE;AAAA,IAAA;AAExD,UAAM,sBAAsB,IAAI,gBAAgB,OAAO,SAAS,MAAM;AAKtE,UAAM,uBAAuB,IAAI,gBAAgB;AAAA;AAAA;AAAA,MAG/C,GAAG,OAAO,YAAY,mBAAmB;AAAA;AAAA;AAAA,MAGzC,GAAG,OAAO,YAAY,mBAAmB;AAAA,IAAA,CAC1C;AAED,QAAI,qBAAqB,OAAO,GAAG;AACjC,aAAO,QAAQ;AAAA,QACb,CAAA;AAAA,QACA;AAAA,QACA,GAAG,OAAO,SAAS,QAAQ,IAAI,qBAAqB,UAAU;AAAA,MAAA;AAAA,IAElE;AAAA,EAEF,GAAG,CAAC,KAAK,UAAU,eAAe,CAAC,CAAC;AAEpC,SAAO;AACT;"}