UNPKG

state-in-url

Version:

Store state in URL as in object, types and structure are preserved, with TS validation. Same API as React.useState, wthout any hasssle or boilerplate. Next.js@14-15, react-router@6-7, and remix@2.

2 lines (1 loc) 1.02 kB
import s from"react";import{useNavigate as g,useSearchParams as k,useHref as P}from"react-router-dom";import{parseSPObj as h}from"../../parseSPObj.mjs";import{useUrlStateBase as C}from"../../useUrlStateBase/useUrlStateBase.mjs";import{routerHistory as H,filterUnknownParamsClient as R,assignValue as d,filterUnknownParams as j}from"../../utils.mjs";function w(t,a){const i=a?.useHistory;const o=s.useMemo(()=>({...y,replace:a?.replace,preventScrollReset:a?.preventScrollReset}),[]);const n=g();const m=s.useMemo(()=>i?H:{replace:(e,r)=>n(e,{...o,...r}),push:(e,r)=>n(e,{...o,...r})},[n]);const[c]=k();const f=P("/");const{state:S,updateState:l,updateUrl:u,getState:U,reset:p}=C(t,m,({parse:e})=>e(R(t,c.entries())),f);const b=s.useCallback((e,r)=>u(e,{...o,...r}),[u]);s.useEffect(()=>{l(d(t,j(t,h(Object.fromEntries([...c.entries()]),t))))},[c]);const v=s.useCallback(e=>{p({...o,...e})},[p]);return{setState:l,setUrl:b,urlState:S,reset:v,getState:U}}const y={replace:true,preventScrollReset:true};export{w as useUrlState};