File tree 1 file changed +13
-1
lines changed
packages/nuqs/src/adapters/lib
1 file changed +13
-1
lines changed Original file line number Diff line number Diff line change @@ -78,11 +78,23 @@ export function createReactRouterBasedAdapter(
78
78
}
79
79
function useOptimisticSearchParams ( ) {
80
80
const [ serverSearchParams ] = useSearchParams (
81
+ // Note: this will only be taken into account the first time the hook is called,
82
+ // and cached for subsequent calls, causing problems when mounting components
83
+ // after shallow updates have occurred.
81
84
typeof location === 'undefined'
82
85
? new URLSearchParams ( )
83
86
: new URLSearchParams ( location . search )
84
87
)
85
- const [ searchParams , setSearchParams ] = useState ( serverSearchParams )
88
+ const [ searchParams , setSearchParams ] = useState ( ( ) => {
89
+ if ( typeof location === 'undefined' ) {
90
+ // We use this on the server to SSR with the correct search params.
91
+ return serverSearchParams
92
+ }
93
+ // Since useSearchParams isn't reactive to shallow changes,
94
+ // it doesn't pick up changes in the URL on mount, so we need to initialise
95
+ // the reactive state with the current URL instead.
96
+ return new URLSearchParams ( location . search )
97
+ } )
86
98
useEffect ( ( ) => {
87
99
function onPopState ( ) {
88
100
setSearchParams ( new URLSearchParams ( location . search ) )
You can’t perform that action at this time.
0 commit comments