Skip to content

[Bug]: useSearchParams reverts to default value when removing the last value #9668

Closed
@eddiemonge

Description

@eddiemonge

What version of React Router are you using?

6.4.4

Steps to Reproduce

Link to example (edit mode)

  1. Call useSearchParams with a default initialization like const [searchParams, setSearchParams] = useSearchParams({ option: 'One' });
  2. Change the value of searchParams.get('option'). The value should change to the new value
  3. Remove the param key. The value should be remove. In actuality, the default initialization is restored
import * as React from 'react';
import { useSearchParams } from 'react-router-dom';

export default function App() {
  const [searchParams, setSearchParams] = useSearchParams({ option: 'One' });
  console.log('initial search params', searchParams.toString())

  const handleChange = ({ target: { value } }: React.ChangeEvent<HTMLInputElement>) => {
    if (value !== 'All') {
      console.log('Setting the option to', value)
      setSearchParams({ option: value});
    } else {
      console.log('Clearing the option')
      setSearchParams({});
    }
  };

  return (
    <div>
      <h1>Search Param Value</h1>
      <p>{searchParams.toString()}</p>
      <h1>Choose an option</h1>
      {['One', 'Two', 'All'].map((s) => (
        <div key={s}>
          <label>
            <input
              checked={searchParams.get('option') === s}
              name="choice"
              onChange={handleChange}
              type="radio"
              value={s}
            />
            <span>{s}</span>
          </label>
        </div>
      ))}
    </div>
  );
}

Expected Behavior

The search params would be blank and searchParam would be an empty object-ish.

Actual Behavior

searchParam reverts to option: 'One'

edited to include a working example of the bug and instructions Jan 23, 2023

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions