How can I remove or update query params without refreshing the page in Next JS (React)?
/about?login=success&something=yes
?login=success&something=yes
from the URL without refreshing the page. The URL after clicking the button will be /about
How can I achieve it?
As mentioned in this thread, I know that is possible to remove query params or query strings with Router. But, useLocation
and useHistory
are not avaliable on next/router
.
You can use next/router
to remove or update the query params in the URL.
const router = useRouter();
router.replace('/about', undefined, { shallow: true });
Use replace
to prevent adding a new URL entry into the history (otherwise just use push
), and shallow: true
allows you to change the URL without running data fetching methods. This will cause a re-render but will not refresh the page per se.
If you want remove single or multiple params from query,
const router = useRouter();
/**
* If removeList is empty, the function removes all params from url.
* @param {*} router
* @param {*} removeList
*/
const removeQueryParamsFromRouter = (router, removeList = []) => {
if (removeList.length > 0) {
removeList.forEach((param) => delete router.query[param]);
} else {
// Remove all
Object.keys(object).forEach((param) => delete object[param]);
}
router.replace(
{
pathname: router.pathname,
query: router.query
},
undefined,
/**
* Do not refresh the page
*/
{ shallow: true }
);
};
const anyFunction = () => {
// "/about?firstParam=5&secondParam=10"
removeQueryParamsFromRouter(router, ['myParam']);
// "/about?secondParam=10"
};
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