react-router icon indicating copy to clipboard operation
react-router copied to clipboard

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

Open eddiemonge opened this issue 3 years ago • 0 comments

What version of React Router are you using?

6.4.4

Steps to Reproduce

Create a hook using useSearchParams with a default initialization like

export function useSearch () {
  return useState<useChannelsState[query]>({ option: 'one' });
}

Then in a component, remove option and try to set the params. It will revert to the default initialization instead of being empty.

import {
  FormControl,
  FormControlLabel,
  Radio,
  RadioGroup
} from '@mui/material';

export function ListView() {
  const [searchParams, setSearchParams] = useSearch();

  const handleChange = ({ target: { value } }: React.ChangeEvent<HTMLInputElement>) => {
    setSearchParams({ ...(value !== 'ALL' && { option: value }) });
  };

  return (
    <FormControl>
      <FormLabel>Options</FormLabel>
      <RadioGroup
        onChange={handleChange}
        row
        value={typeof searchParams.option === 'undefined' ? 'ALL' : searchParams.option}
      >
        {['One', 'Two', 'All'].map((s) => (
          <FormControlLabel
            control={<Radio />}
            key={s}
            label={s}
            value={s}
          />
        ))}
      </RadioGroup>
    </FormControl>
  };
}

Expected Behavior

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

Actual Behavior

searchParam reverts to option: 'one'

eddiemonge avatar Dec 02 '22 21:12 eddiemonge