I have an app which sometimes is loaded with a query string param t.
At the start, I want the app to read this param if available and remove it from the URL.
On the root component, I am doing this:
const [searchParams, setSearchParams] = useSearchParams();
if (searchParams.has('t')) {
const token = searchParams.get('t');
if (token) {
searchParams.delete('t');
const newParams: {[key: string]: string} = {};
searchParams.forEach((value: string, key: string) => {
newParams[key] = value;
});
console.log('setting params: ');
console.dir(newParams);
setSearchParams(newParams);
AuthController.setAccessToken(token);
}
}
I see that it correctly reads param t and the newParams object is empty or contains only the other parameters, but for some reason setSearchParams(newParams) seems to not be doing anything. Parameter t is still in the URL.
How I can have it remove this parameter from the URL?
The setSearchParams updater function effectively is "navigate" but for only the queryString portion of the URL.
useSearchParams
Note:
The
setSearchParamsfunction works likenavigate, but only for the search portion of the URL. Also note that the second arg tosetSearchParamsis the same type as the second arg tonavigate.
You don't need to call navigate to update the queryString. The issue is doing this logic as an unintentional side-effect. Move all the logic into a useEffect hook and you'll find it works as you were expecting.
const [searchParams, setSearchParams] = useSearchParams();
useEffect(() => {
if (searchParams.has("t")) {
const token = searchParams.get("t");
if (token) {
searchParams.delete("t");
console.log("setting params:", { searchParams: searchParams.toString() });
console.dir(searchParams.toString());
setSearchParams(searchParams);
}
}
}, []);
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