Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a value in query in Next.js

I am using Next js. I create the url using query params: http://localhost:3000/cars?colors=red&nr=20. Is there a possibility, when i click on the button, to change just a specific part of the url like: http://localhost:3000/cars?colors=blue&nr=20. So in this case i just changed the color in blue. I used:

  router.replace(
      {
        pathname: '/...',
        query:  {
          color: blue
        },
      },
      undefined,
      {
        shallow: true,
      },
    );

but it does not work.
How to solve the issue?

like image 721
Asking Avatar asked Apr 09 '26 04:04

Asking


1 Answers

you will need to add all the queries into your router.replace query, e.g.

  router.replace(
  {
    pathname: '/...',
    query:  {
      nr:20,
      color: blue
    },
  },
  undefined,
  {
    shallow: true,
  },
);

to make it simpler, you can do

  router.replace(
  {
    pathname: '/...',
    query:  {
      ...router.query, // list all the queries here
      color: blue // override the color property
    },
  },
  undefined,
  {
    shallow: true,
  },
);
like image 114
Sabrina Luo Avatar answered Apr 10 '26 23:04

Sabrina Luo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!