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

Passing value `undefined` does not clear internal state

Open douweknook opened this issue 8 years ago • 19 comments

I'm working on a project where we use a react-select Select component together with 2 radio inputs (see screenshot below). When the other radio is selected we set the value for the select in our local state to undefined using the onChange handler. So we pass the properties value={undefined} and no defaultValue. We also set isClearable={false}, isSearchable={false} and if the value is undefined isDisabled={true}. As you can see the value of the Select component is not cleared and set back to the placeholder.

schermafbeelding 2018-09-25 om 12 14 33

When inspecting the components react-select creates with the React devtools I noticed the props and state of the StateManager look like this: schermafbeelding 2018-09-25 om 12 16 28

It seems that, even though the value is undefined and the defaultValue is null, the state is not cleared. which is odd as the stateManager.js file includes the following lines:

 state = {
      inputValue:
        this.props.inputValue !== undefined
          ? this.props.inputValue
          : this.props.defaultInputValue,
      menuIsOpen:
        this.props.menuIsOpen !== undefined
          ? this.props.menuIsOpen
          : this.props.defaultMenuIsOpen,
      value:
        this.props.value !== undefined
          ? this.props.value
          : this.props.defaultValue,
    };

So this.state.value should be null. And then the following code is used to get that value and pass it to the Select component:

getProp(key: string) {
      return this.props[key] !== undefined ? this.props[key] : this.state[key];
    }

so it should still be null as far as I can tell.

I cannot really explain why this happens but figured I'd make an issue as it feels like a bug. If it's not and I forgot to pass some prop correctly I'd also be happy to hear it :)

Ultimately we solved this for our use case by adding a key prop to our Select component so that it remounts when the value changes which does clear the value and sets it back to the placeholder. This works but it is not the nicest fix of course.

douweknook avatar Sep 25 '18 10:09 douweknook

Thanks @douweknook for the key workaround

mcarlone avatar Oct 02 '18 20:10 mcarlone

I've also been running into this. Prior to v2 we mapped all values to the value key, but with the 2.0 changes that only allow an object for the value key, many of our selects changed:

Given these example options:

let options = [
  {label: 'zero', value: 0},
  {label: 'one', value: 1},
  {label: 'two', value: 2}
]

we went from

<Select
    options={options}
    value={this.state.value}
    onChange={option => this.setState({value: option.value})}

to

<Select
    options={options}
    getOptionValue={option => option.value}
    getOptionLabel={option => option.label}
    onChange={option => this.setState({value: option.value})}
    value={options.find(o => o.value === this.state.value)}
>

since the value prop is required to be a full object in v2, instead of just a string as we were setting before.

The only way I've found to work around it is by setting value={options.find(o => o.value === this.state.value) || '') but it's definitely a bit duct-tapey.

Though our upgrade solution is a bit non-standard, I would still think that the value being changed to undefined should get reflected in the Select's internal state, instead of holding onto the last value.

blairmorris avatar Oct 15 '18 19:10 blairmorris

This duct-tape solved the problem for me as well. Thank you for this solution~

whatrocks avatar Oct 24 '18 00:10 whatrocks

Update: In recently updated docs, it says in a piece about upgrading from old key/label props to use value={options.filter(({value}) => value === this.state.value)} instead when using simple values, and I've found that it works infinitely better than value={options.find(({value}) => value === this.state.value) || ''}

blairmorris avatar Oct 30 '18 20:10 blairmorris

The API docs say the type for value is

One of <
  Object,
  Array<Object>,
  null,
  undefined
>

That agrees with ValueType in the code:

export type ValueType = OptionType | OptionsType | null | void;

I would expect null or undefined to clear the selection, but it does not.

jamesarosen avatar Mar 14 '19 19:03 jamesarosen

I agree with @jamesarosen - both null and undefined should clear the selection.

We wrap the Select component so my solution to this issue was to provide null as a default prop:

function Wrapper ({
  value = null,
  ..rest
}) {
  return (
    <Select value={value} {...rest} />
  );
}

jacobworrel avatar Aug 01 '19 16:08 jacobworrel

any updates regarding this? Im facing the same thing. "Country" selector should clear "State" selector on change, but the latter just retains its last value despite setting it to null/undefined

andresmatasuarez avatar Sep 20 '19 19:09 andresmatasuarez

If you get a ref to the StateManager, you can do it like this:

<Select
  ref={(ref) => { this.selectRef = ref }}
  ...
/>

Then make the call when you want to clear it.

this.selectRef.onChange(undefined, { action: 'clear' })

pgib avatar Oct 05 '19 00:10 pgib

@pgib thanks for your answer. What you propose seems definitely better than keeping a key in state and updating it to clear the selector. Sadly, it still looks like a hack :(. I can't believe so common a use case is not being handled by default by the library

andresmatasuarez avatar Oct 05 '19 01:10 andresmatasuarez

Yeah, it's totally a hack, but at least it's doing it in the same way as the clear button. Ideally you shouldn't have to dig through the source code to do something so basic. 🤷‍♂️

pgib avatar Oct 05 '19 01:10 pgib

Or, using the above example, once you have the ref assigned to the component you can execute this code to clear/reset the select:

this.selectRef.select.clearValue();

NoahDavidATL avatar Oct 15 '19 20:10 NoahDavidATL

When using Select as uncontrolled component the above hack with the clearValue() did not work for me. What worked was setting the value as null.

You can see the comparison here: https://codesandbox.io/s/epic-matsumoto-3p6j2

apieceofbart avatar Dec 09 '19 13:12 apieceofbart

Also running into this and can confirm using null instead of undefined works. As a workaround I'm just converting null to undefined in my HOC wrapper's onChange.

kalbert312 avatar Dec 30 '19 15:12 kalbert312

Got this same issue today, can verify that using null instead of undefined did the trick.

yagudaev avatar Jun 03 '20 23:06 yagudaev

Setting the value to null works for me.

aohua avatar Jun 08 '20 04:06 aohua

Can confirm the bug too.

khanilov avatar Jun 11 '20 09:06 khanilov

In normal React way, having the value prop with a value of undefined on a form element indicates it being uncontrolled, meaning it does not rely on a prop for its value. React would give you an error in the console if you change the value of the value prop on a form element to undefined (switching from controlled to uncontrolled). react-select instead gracefully switches to being uncontrolled and manages the value by itself.


In short, using undefined to clear the value is in general bad practice. Use null instead when you clear the value of any Select component provided by this library.

Rall3n avatar Jun 12 '20 00:06 Rall3n

As pointed out by @Rall3n, an undefined value is not interchangeable with null.

Due to the inactivity of this issue and apparent discovery/resolution, we will be closing this. If there are any other followups regarding this confusion, please feel free to open a Discussion in the discussions section.

ebonow avatar Dec 04 '20 02:12 ebonow

For new people the TLDR: As of 5.8.0 in a controlled Select component setting the value to null clears the text (but undefined doesn't).

bali182 avatar Oct 14 '24 08:10 bali182