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