useUrlState: prevent existing URL queries from being deleted by useUrlState
If I use this hook, it may erase existing queries. It is possible to provide some options to change this behavior?
// test.com?a=1
const [urlState, setUrlState] = useUrlState({}, { navigateMode: 'replace' })
useEffect(() => {
setUrlState({
foo: 'bar' // test.com?foo=bar
})
})
If I use the result of useSearchParams as initialState, it may work. However, the component does not rerender every time.
please try this:
setUrlState((prevState) => ({
...prevState,
foo: 'bar'
}));
prevState may not work since previous state does not contain all the queries in URL. Like the code above, URL has a query call a. However, if I do not pass current queries into useUrlState, it will not work. Currently, I use this method to avoid missing queries
setUrlState({
...Object.fromEntries(
new URL(window.location.toString()).searchParams
),
foo: 'bar'
})
It will set the latest queries all the time
I tested the useUrlState hook in a demo project, but was unable to reproduce your situation:
https://github.com/alibaba/hooks/assets/38221479/4d005ea0-60c7-43fb-9064-2610131f4e7a
Both hash router and browser router were tested.
So can your confirm this problem further? thanks. It would be better to provide an online demo to reproduce this issue