@thibault.sh/hooks
Version:
A comprehensive collection of React hooks for browser storage, UI interactions, and more
2 lines • 965 B
JavaScript
import {useCallback,useState,useEffect}from'react';function v(t,n,w={}){let{serialize:s=JSON.stringify,deserialize:i=JSON.parse}=w,a=useCallback(()=>{if(typeof window=="undefined")return n;try{let r=new URLSearchParams(window.location.search).get(t);return r?i(r):n}catch(e){return console.warn(`Error reading query parameter "${t}":`,e),n}},[t,n,i]),[o,c]=useState(a),p=useCallback(e=>{try{let r=e instanceof Function?e(o):e;if(c(r),typeof window!="undefined"){let d=new URLSearchParams(window.location.search);d.set(t,s(r));let l=`${window.location.pathname}?${d.toString()}`;window.history.pushState({},"",l);}}catch(r){console.warn(`Error setting query parameter "${t}":`,r);}},[t,s,o]);return useEffect(()=>{let e=()=>{c(a());};return window.addEventListener("popstate",e),()=>window.removeEventListener("popstate",e)},[a]),[o,p]}export{v as useQueryParamsState};//# sourceMappingURL=useQueryParamsState.mjs.map
//# sourceMappingURL=useQueryParamsState.mjs.map