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
.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With