7

I need a Async react-select, which will loadOptions from backend and users will be able to select multiple options. However when inputValue is already entered and users clicks on select input options is not being loaded. They are loaded only when you type something in.

Example code sandbox

Input value stays the same

EDIT: answer

To reload default options you need to pass defaultOptions to Async select, not just true. This can be done by setting defaultOptions to state in componentDidMount and listening for 'menu-close' action in onInputChange and setting defaultOptions to state there. This will ensure that when the component is mounted the defaultOptions will be there, and when menu is closed, the options will be refetched with new inputValue.

2 Answers 2

8

To have react-select autoload content you must provide the defaultOptions prop. If you don't autoload then it won't make your async call until they attempt to filter.

<AsyncSelect loadOptions={myAsyncMethod} defaultOptions />
3
  • Thanks for the answer. It works on first load, however if i change inputValue, then clear the input, options list stays the same. I've added additional sandbox.
    – Simas.B
    Oct 19, 2018 at 16:22
  • 1
    That gives me some more info. Though you can set inputValue through props, it's not immediately recognized in react-select lifecycle, and inputValue state is already controlled inside the component. Also the loadOptions method takes the inputValue as an argument, and this is what you would use in your filter. What's your reason behind trying to control the inputValue externally? I forked your example to show some working usage on the filtering you were trying to show. codesandbox.io/s/rr00y31k7q Oct 19, 2018 at 19:34
  • Our select will query users from BE. And selected users will be selected into list. So f.e. user enters department name, and wants to select multiple users from it, i'd like the input value to not disappear when user selects user, or input loses focus, so the user wouldn't have to enter department on each occasion.
    – Simas.B
    Oct 22, 2018 at 7:30
4

To reload default options you need to pass defaultOptions to Async select, not just true. This can be done by setting defaultOptions to state in componentDidMount and listening for 'menu-close' action in onInputChange and setting defaultOptions to state there. This will ensure that when the component is mounted the defaultOptions will be there, and when menu is closed, the options will be refetched with new inputValue.

Working example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.