4

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.

4 Answers 4

8

To remove the query param completely from the url:

const { paramToRemove, ...routerQuery } = router.query;
router.replace({
  query: { ...routerQuery },
});
Sign up to request clarification or add additional context in comments.

1 Comment

This works like a charm, answer didn't work correctly for me, pay attention that paramToRemove is expected to be an object, you can grab it before like const { nameOfQueryParam } = router.query;
4

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.

2 Comments

Sorry, I wasn't completely clear in my question. This might work, but if I want to remove the search query in my app by clicking "clear", then the router.push runs (that you posted) and type + category will still show up as empty IF there is no type or category query in the url yet. Right?
Yes. I've updated my answer to handle cases where the other query params aren't in the URL yet.
2

You can just remove it by deleting the property in router.query

delete router.query.search;
router.push(router);

2 Comments

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
This won't remove the query parameter from url, but indeed remove it from router
0

let queries = Object.assign({}, router.query);

delete queries.search;
return router.push(
      {
         pathname: `/`,
         query: queries
      },
      "",
      { scroll: false }
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.