Update multiple existing query params, instead of setting the search params to an entirely new value

Firstly I set up the query params with searchParams using react-router-dom v6

const [searchParams, setSearchParams] = useSearchParams()

const type = searchParams.get("type")
const price = searchParams.get("price")
const availability = searchParams.get("availability")
const location = searchParams.get("location")

After that I’m using a select input to set different query params

<Select placeholder='Select car type' onChange={(e) => setSearchParams({type: e.target.value})}>
   <option value='suv'>SUV</option>
   <option value='sedan'>Sedan</option>
   <option value='hatchback'>Hatchback</option>
</Select>
         
<Select placeholder='Select price range' onChange={(e) => setSearchParams({price: e.target.value})}>
   <option value={[10, 30]}>10$ - 30$ / day</option>
   <option value={[31, 60]}>31$ - 60$ / day</option>
   <option value={[61, 100]}>61$ - 100$ / day</option>
</Select>

When selecting the first select input the query is being set correctly as followed

/search?type=suv

But when selecting the second select input instead of getting this:

/search?type=suv&price=10%2C30

I get this:

/search?price=10%2C30

I’m not updating, but setting a new query param, how can i update the params instead of setting a new one…

>Solution :

Use the callback update function to set the query params. In the callback the current searchParams value is passed and can be updated and returned.

Example:

<Select
  placeholder='Select car type'
  onChange={(e) => {
    setSearchParams(searchParams => {
      searchParams.set("type", e.target.value);
      return searchParams;
    });
  }}
>
  <option value='suv'>SUV</option>
  <option value='sedan'>Sedan</option>
  <option value='hatchback'>Hatchback</option>
</Select>
         
<Select
  placeholder='Select price range'
  onChange={(e) => {
    setSearchParams(searchParams => {
      searchParams.set("price", e.target.value);
      return searchParams;
    });
  }}
>
  <option value={[10, 30]}>10$ - 30$ / day</option>
  <option value={[31, 60]}>31$ - 60$ / day</option>
  <option value={[61, 100]}>61$ - 100$ / day</option>
</Select>

Leave a Reply