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