When I provide loadOptions
to an Async
control it loads options on mount.
If I pass autoload={false}
then it doesn't load options neither on mount nor on open. But it loads options on the first close (or type, or blur).
If I pass onCloseResetsInput={false}
then it doesn't load options until I type something. (showing "Type to search" in the menu)
Async
provides onOpen
handler, but I didn't find the way to use it in this situation. (and [email protected]
doesn't have it)
So the user needs to type a character, then delete it, to see the full list of options.
How can this be avoided?
Example sandbox: https://codesandbox.io/s/mjkmowr91j
Solution demo: https://codesandbox.io/s/o51yw14l59
I used the Async options loaded externally
section from the react-select repo.
We start by loading the options on the Select's onFocus
and also set the state to isLoading: true
. When we receive the options we save them in the state and render them in the options.
I also keep track of optionsLoaded
so that only on the first focus
do we trigger the call to get options.
In our use case, we have several of these select inputs on a single page, all async, so the requests to the server will pile up, and are completely unnecessary in a lot of cases (users won't even bother clicking).
I found a workaround for this issue that'll work for my use case on 2.0.0-beta.6:
defaultOptions
resolve
/reject
methods for the promise.loadOptions
function, check if the input is '', if so, create a new promise, and store the values of resolve
/reject
within your class members, and return that promise. Otherwise, just return the promise normally to get your results..then
and .catch
callbacks passing the resolve
and reject
functions you stored previously.Essentially, this makes react-select think you're working on getting the results with a long-running promise, but you don't actually even try to load the values until the field is selected.
I'm not 100% positive there aren't any negative side effects as I just wrote this, but it seems like a good place to start.
Hope this helps someone. I may submit a feature request for this.
In order to load options when user focus first time, set defaultOptions={true}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With