http://localhost:3000/?search=test&type=abc&category=xyz
After I search for test (among with type and category), the URL changes to the URL above.
return router.push(
{
pathname: `/`,
query: {
// something to do here...
},
},
"",
{ scroll: false }
);
Next, I have an onClick with this router.push.
I would like to remove ONLY the search query and keep the type and category queries. How is it possible? The documentation doesn't mention anything about this.
You can call router.push with the current query string, but omitting the search parameter.
const params = new URLSearchParams(router.query);
params.delete('search');
const queryString = params.toString();
const path = `/${queryString ? `?${queryString}` : ''}`;
router.push(path, '', { scroll: false });
Given that you're currently at /?search=test&type=abc&category=xyz, the above will route you to /?type=abc&category=xyz. This will also handle scenarios where the type and category query parameters aren't present.
let queries = Object.assign({}, router.query);
delete queries.search;
return router.push(
{
pathname: `/`,
query: queries
},
"",
{ scroll: false }
);
To remove the query param completely from the url:
const { paramToRemove, ...routerQuery } = router.query;
router.replace({
query: { ...routerQuery },
});