Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-router v6 extending search params instead of replacing it

Currently, doing setSearchParams(/* an object */) will replace the existing search params. If I would like to extend the search params instead of replacing them, e.g. adding a new param. What will be the most elegant way to achieve that?

I know I can modify the searchParams directly, then do something like setSearchParams(newSearchParamsToObject). Yet, since searchParams is not an object but a URLSearchParams. The code will be long and ugly.

Edit: Since some one appears don't understand what I have posted

Currently if we do something like this:

const [searchParams, setSearchParams] = useSearchParams({ a: 1 });
setSearchParams({ b: 2 });

It will replace the searchParams with ?b=2.

What I would like to achieve is adding b=2 to existing search params, i.e. the final search params should be ?a=1&b=2.

like image 611
Matthew Kwong Avatar asked Sep 01 '25 02:09

Matthew Kwong


1 Answers

I suppose it would/should be trivial to set the search param value you want to add.

const [searchParams, setSearchParams] = useSearchParams();

...

searchParams.set(newParamKey, newParamValue);
setSearchParams(searchParams);

Edit react-router-v6-extending-search-params-instead-of-replacing-it

const [searchParams, setSearchParams] = useSearchParams();

const clickHandler = () => {
  searchParams.set("b", 2);
  setSearchParams(searchParams);
};

...

<button type="button" onClick={clickHandler}>
  Add "b=2" param
</button>

Introduced in [email protected] the setSearchParams now also takes a function, similar to the useState hook, to access the previous query params object to update from.

setSearchParams(searchParams => {
  searchParams.set("b", 3);
  return searchParams;
});

This is handy if you are using the setSearchParams in a useEffect hook as you won't need to list the current searchParams object as an external dependency.

like image 161
Drew Reese Avatar answered Sep 02 '25 16:09

Drew Reese