Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NEXT JS - How to remove Query Params?

How can I remove or update query params without refreshing the page in Next JS (React)?

  1. The user is on the URL /about?login=success&something=yes
  2. Click a button and removes ?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.

like image 602
Alfrex92 Avatar asked Jan 07 '21 05:01

Alfrex92


Video Answer


2 Answers

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.

like image 149
juliomalves Avatar answered Sep 23 '22 14:09

juliomalves


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"
};

like image 39
Muhammet Can TONBUL Avatar answered Sep 19 '22 14:09

Muhammet Can TONBUL