hooks icon indicating copy to clipboard operation
hooks copied to clipboard

useUrlState: prevent existing URL queries from being deleted by useUrlState

Open zzzzzhowie opened this issue 2 years ago • 3 comments

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.

zzzzzhowie avatar Nov 01 '23 04:11 zzzzzhowie

please try this:

setUrlState((prevState) => ({
    ...prevState,
    foo: 'bar'
}));

liuyib avatar Nov 02 '23 01:11 liuyib

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

zzzzzhowie avatar Nov 02 '23 10:11 zzzzzhowie

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

liuyib avatar Nov 06 '23 03:11 liuyib