-1

I am using useSearchParams (react-router-dom@6). When I add a new query parameter it deletes the previous ones. How can I prevent this?

When I try this

const filterFunc = (valu) => {
  setSearchParams({ star: valu });
}

this is happening: http://localhost:3000/products/search?star=1

my expectation: http://localhost:3000/products/search?q=car&star=1

I adapted this answer to my own code, but I don't think it's optimal.
code:

const [searchParams, setSearchParams] = useSearchParams();
const params = {};

searchParams.forEach((value, key) => {
  params[key] = value;
});
const filterFunc = (star) => {
  params["star"] = star;
  setSearchParams(params);
}
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • something like `setSearchParams((prev) => ({...prev, { star: value }}));` might do? – Nsevens Dec 22 '22 at 13:43
  • @Nsevens I tried but it didn't work and the correct spelling is "setSearchParams((prev) => ({ ...prev, star: valu }));" wasn't it – Baki Öztel Dec 22 '22 at 13:51

1 Answers1

0

The searchParams is a URLSearchParams object. You can call any of that object's methods, like append or set, to mutate it.

const [searchParams, setSearchParams] = useSearchParams();

...

const filterFunc = (value) => {
  // Add the new query param value to the queryString
  searchParams.set("star", value);

  // Enqueue navigation action that updates the queryString
  setSearchParams(searchParams);
}

...

I don't know the exact v6 version it was introduced, but the current version of the useSearchParams hook's setURLSearchParams updater function can take a callback function that is passed the previous URLSearchParams object (similar to the React.useState hook functional state update).

const [searchParams, setSearchParams] = useSearchParams();

...

const filterFunc = (value) => {
  // Enqueue navigation action that updates the queryString
  setSearchParams(searchParams => {
    // Add the new query param value to the queryString
    searchParams.set("star", value);
    return searchParams;
  });
}

...
Drew Reese
  • 165,259
  • 14
  • 153
  • 181