Multiple `Router.push` calls don't batch
See original GitHub issueWhat version of Next.js are you using?
11.1.2
What version of Node.js are you using?
v14.15.5
What browser are you using?
Chrome
What operating system are you using?
macOS
How are you deploying your application?
Vercel
Describe the Bug
I’m trying to set query params with Router.push
, with shallow: true
.
I’m calling two separate functions to update query parameters.
setQueryParam('search', '')
setQueryParam('filterCount', '0')
However, this only updates filterCount
. search
is untouched.
Expanded code:
const { push, pathname, query } = useRouter()
const setQueryParam = (param: string, value: string) => {
push(
{
pathname,
query: {
...query,
[param]: value
}
},
undefined,
{
shallow: true
}
)
}
Expected Behavior
I’d expect Router.push
to batch / queue updates the way setState
does. As it stands, the only way to update multiple query param is in a single function call. For complex use cases of multiple query params, this isn’t a good DX.
I’m trying to use query params as my state, but this issue is an impediment for updating more than one state at a time. This is particular difficult when clearing states (ie, you close an artist profile, and want to remove any query params associated with the artist.)
To Reproduce
Here’s a CodeSandbox: https://codesandbox.io/s/distracted-leakey-puqzx?file=/pages/index.tsx
Here’s a video showing what happens: https://www.loom.com/share/eb73a18e747341f3a172fccaca64a6d4
Notice that, if I call setQueryParam
twice, it doesn’t batch the two of them. Instead, only one of the query params (the second one) gets updated.
The only way to update the URL state more than once is to batch these into one single Router.push
call. That’s quite limiting, though.
Issue Analytics
- State:
- Created 2 years ago
- Comments:10 (5 by maintainers)
Top GitHub Comments
Hi, this is the expected behavior for
next/router
as we allow newrouter.push
calls to cancel previous navigations so that a stale pending navigation doesn’t block a new one. As mentioned above it would be good to update the query in one go as this also triggers additional renders in your application or you can wait for therouter.push
promise to resolve before you call it again.I’m gonna close this since it is expected behavior, if you would like to continue discussing potential ways to handle this you can open a help discussion here https://github.com/vercel/next.js/discussions/categories/help which is more suited for this
Yeah, my CodeSandbox actually does use
useRouter
. I oversimplified it in the code sample above, I’ll update it.