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 and react-router@6-7.

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