Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router: Update only one query parameter instead of replacing all

I am trying to update only one query param key-value on button click using react-router (v5).

const btnClickHandler = () =>{
    history.push({ search: 'popup=false' });
}

I want this code to update the url from:

https://base-url.com/?popup=true&checked=true

to:

https://base-url.com/?popup=false&checked=true

but instead, it replaces the whole search to:

https://base-url.com/?popup=false

Basically, instead of replacing all the query param key value, how can I replace only one?

like image 519
Gaurav Avatar asked May 08 '20 18:05

Gaurav


2 Answers

You need to merge the query params yourself before updating them. You could use query-string (https://www.npmjs.com/package/query-string) library to make your job easier.

import qs from 'query-string';

const Component = ({ location}) => {

    const btnClickHandler = () =>{
        const queryParams = qs.parse(location.search);
        const newQueries = { ...queryParams, popup:false};
        history.push({ search: qa.stringify(newQueries) });
    }

 }
like image 170
Shubham Khatri Avatar answered Nov 01 '22 17:11

Shubham Khatri


With the version 6 of react-router-dom, you could:

    const [searchParams, setSearchParams] = useSearchParams();
    let updatedSearchParams = new URLSearchParams(searchParams.toString());
    updatedSearchParams.set('operation', 'edit');
    setSearchParams(updatedSearchParams.toString());
like image 20
rockneverdies Avatar answered Nov 01 '22 15:11

rockneverdies