react-router v6 extending search params instead of replacing it

Viewed 3746

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.

2 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>

Also seems to work:

  • setSearchParams([...searchParams.entries(), ['b', 2]]);

You could also use the URLSearchParams.append(name, value) method, in case you want several 'b'.

setSearchParams(searchParams.append('b', 2));

It's not like your modifying the state, here. You're just manipulating an URLSearchParams object. You don't have to worry about mutating it.

Related