1

I have a structure with a clean URL in the "pages" folder like this ...

/pages/items/[pageNumber]/index.tsx

And if I use router.push I use it like this to get to that page ...

router.replace("/items/[pageNumber]", "/items/1")

That works great, but now I want to add a query params (for filter) to that URL, how can I do that?

I tried this ...

router.push(`/items/[pageNumber]/`, `/items/1/?${filterParams}`, { shallow: true });

But that doesn't work, and I'm wondering how to do that.

Ruby
  • 2,207
  • 12
  • 42
  • 71
  • when you say it's not working, you should state how exactly. Is it that you could not get the query param or the routing is not working, etc. – Joshua Aug 11 '20 at 14:49
  • @Joshua For some reason, the URL changes but the page gets refreshed after 3 seconds. – Ruby Aug 11 '20 at 14:50
  • @Joshua I'm wondering is what I'm doing is correct, if it is correct, I should look for the problem elsewhere, but I'm not sure if that is correct or not. – Ruby Aug 11 '20 at 14:51
  • check this stackoverflow question https://stackoverflow.com/a/61470662/6220015 – Joshua Aug 11 '20 at 15:09

1 Answers1

3

When you use it like this

router.push(`/items/[pageNumber]/`, `/items/1/?${filterParams}`, { shallow: true });

you are not passing query params to the page, you are only showing them in the address bar, I guess.

How about something like this:

router.push({
  pathname '/items/[pageNumber]/',
  query: {
    param1: 'yes',
  },
}, {
  pathname: '/items/1/',
  query: {
    param1: 'yes',
  },
});

Don't forget to update query part for your case.

Gokhan Sari
  • 7,185
  • 5
  • 34
  • 32
  • Ok, but the thing is I have no idea what kind of filter params I'm going to receive, it could be ?typ=1,2, or ?type=1,2&make=2,3, so I need it to be dynamic, how can I do that? – Ruby Aug 11 '20 at 14:57
  • I don't know where do you get those from but, you can go with something like `{ type: '1,2' }` or `{ type: '1,2', make: '2,3' }`? – Gokhan Sari Aug 11 '20 at 14:59
  • When I try your solution, the URL changes but the page refreshes itself after 3 seconds for some reason. – Ruby Aug 11 '20 at 15:05
  • Well, I updated Next.js and re-ran the project and the page doesn't refresh anymore, which is good, I'll try your solution and see if it works. – Ruby Aug 11 '20 at 15:32
  • Your solution worked great, and I found out why the page reloads a few seconds after the query params changes, here's the link to the issue if anyone stumbles on this thread ... https://github.com/vercel/next.js/issues/9958 – Ruby Aug 13 '20 at 07:05