@@ -46,13 +46,6 @@ export function useUrlState<T extends DefaultSchema>(
4646 ( ) => new GenericRouter ( update , { } ) ,
4747 ) ;
4848
49- useEffect ( ( ) => {
50- router . init ( ) ;
51- return ( ) => {
52- router . destroy ( ) ;
53- } ;
54- } , [ router ] ) ;
55-
5649 return useUrlStateWithRouter ( schema , initialValue || null , {
5750 applyInitialValue : false ,
5851 ...options ,
@@ -66,7 +59,6 @@ export function useUrlStateWithRouter<T extends DefaultSchema>(
6659 options : UrlStateOptions & { router : UrlStateRouter } ,
6760) : UrlState < T > & UrlStateMethods < T > {
6861 const schemaRef = useRef ( schema ) ;
69-
7062 const cachedInitialValue = useShallowEqualValue ( initialValue ) ;
7163
7264 const [ state , setState ] = useState < UrlState < T > > ( {
@@ -76,6 +68,7 @@ export function useUrlStateWithRouter<T extends DefaultSchema>(
7668 isReady : false ,
7769 } ) ;
7870
71+ // needed it order to make handler functions stable
7972 const stateRef = useRef ( state ) ;
8073 stateRef . current = state ;
8174
@@ -86,7 +79,7 @@ export function useUrlStateWithRouter<T extends DefaultSchema>(
8679 const validationResult = schemaRef . current . safeParse ( object ) ;
8780
8881 const result = validationResult . success
89- ? { success : true , data : validationResult . data , error : null }
82+ ? { success : true , data : validationResult . data ?? null , error : null }
9083 : { success : false , data : object , error : validationResult . error } ;
9184
9285 setState ( {
@@ -105,28 +98,34 @@ export function useUrlStateWithRouter<T extends DefaultSchema>(
10598 } ;
10699 } , [ recalculateState ] ) ;
107100
101+ useEffect ( ( ) => {
102+ if ( state . isReady ) {
103+ options . router . init ( ) ;
104+ }
105+ return ( ) => {
106+ options . router . destroy ( ) ;
107+ } ;
108+ } , [ options . router , state . isReady ] ) ;
109+
108110 const push = usePush ( options . router ) ;
109111
110112 const handlers = useHandlers < T > ( push , stateRef ) ;
111113
112114 // set the state from initial url
113115 useEffect ( ( ) => {
114- if ( ! cachedInitialValue ) {
115- update ( window . location . search ) ;
116- } else if (
117- state . isReady &&
118- options . applyInitialValue &&
119- cachedInitialValue &&
120- searchIsEmpty ( window . location . search )
121- ) {
122- handlers . setState ( { ...state . data , ...cachedInitialValue } ) ;
116+ const searchString = window . location . search ;
117+
118+ if ( ! searchIsEmpty ( searchString ) ) {
119+ update ( searchString ) ;
120+ } else if ( cachedInitialValue && options . applyInitialValue ) {
121+ handlers . setState ( cachedInitialValue ) ;
123122 } else {
124123 setState ( ( st ) => ( {
125124 ...st ,
126125 isReady : true ,
127126 } ) ) ;
128127 }
129- } , [ state . isReady , cachedInitialValue , options . applyInitialValue ] ) ;
128+ } , [ cachedInitialValue , options . applyInitialValue ] ) ;
130129
131130 return { ...state , ...handlers } ;
132131}
0 commit comments