Yone
Yone

Reputation: 976

How to keep options state after losing focus on async-select?

Using the component of 'react-select' I have troubles with the options state. After the 'blur' event the options are set to the default ones, however the inputValue is still set. How to avoid such an options reset?

"react" 16.8.6 "react-select" 2.4.2

I provide all the props to the components according to the docs https://react-select.com/props#async-props, including loadOptions returning Promise, that resolves with options list, defaultOptions as true, cacheOptions as true, inputValue from my component's state, onInputChange changing the state's inputValue on the actions except 'input-blur' and 'menu-close'.

onInputChange = (inputValue, { action }) => {
  if (!['input-blur', 'menu-close'].includes(action)) {
    this.setState({ inputValue });
  }
};
loadOptions = input => {
  return getOptions(input);
};
<Async
  cacheOptions,
  defaultOptions,
  onInputChange={onInputChange}
  loadOptions={loadOptions}
  inputValue={inputValue}
>

I expect the options after 'focus' to be kept same as before 'blur', but options are set to default.

Upvotes: 3

Views: 2318

Answers (2)

Sergio
Sergio

Reputation: 1

Another solution i've just found is to store in a state the response to return on loadOptions, and pass it as a prop as "defaultOptions". Following your code:

const [defaultOptions, setDefaultOptions] = useState();
loadOptions = input => {
  const res = getOptions(input);
  setDefaultOptions(res);
  return res;
};

And:

<Async
  cacheOptions
  defaultOptions={defaultOptions}
  onInputChange={onInputChange}
  loadOptions={loadOptions}
  inputValue={inputValue}
>

Upvotes: 0

Yone
Yone

Reputation: 976

The docs provided for props of <Async> onChangeInput are not totally correct.

function (
  string,
  {
    action required One of <
      "set-value",
      "input-change",
      "input-blur",
      "menu-close"
    >
  }
) => undefined

It's not always undefined expected to be returned from the function.

When handling the change <Async> gets the inputValue returned from onInputChange. Returning inputValue from my state solved the problem for me.

Upvotes: 3

Related Questions