Rao Asim
Rao Asim

Reputation: 330

Shallow routing not working as expected in nextjs

I am trying to change the query params using router.push without reloading the page. I tried using shallow routing as suggested by nextjs docs but it is not working as expected. It should be noted that I am using dynamic routing. So my url looks like this

http://localhost:3000/category/865/940/940?parentId=940

and as it is dynamic, the slug url would look like this

http://localhost:3000/category/[category]/[subCategory]/[productCat]?parentId=940

Now when I try shallow routing, it adds the query param but my url becomes something like this:

http://localhost:3000/category/[category]/[subCategory]/[productCat]?parentId=940&price=333

It should be like this:

http://localhost:3000/category/865/940/940?parentId=940&price=333

I used shallow in accordance to nextjs docs such as: router.push("&price=sdds", undefined, { shallow: true,})

but it giving me a weird url and refreshes the page.

Upvotes: 1

Views: 1812

Answers (1)

Lakshya Thakur
Lakshya Thakur

Reputation: 8316

The usage of router.push seems incorrect to me. From the docs, the syntax is :-

router.push(url, as, options).

But you are using it as router.push("&price=sdds", undefined, { shallow: true,}) and not passing the url.

You can try the below syntax to just add the new query param to your existing url (The first parameter to router.push can be an object as well according to the docs) :-

const newQuery = {
  ...router.query,
  price: newPrice,
};

router.push(
  {
    pathname: router.pathname,
    query: newQuery,
  },
  undefined,
  { shallow: true }
);

Upvotes: 1

Related Questions