Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load options on the first open of the Async drop down menu

Tags:

react-select

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

like image 809
xiety Avatar asked Feb 01 '18 14:02

xiety


3 Answers

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.

like image 51
Alexei Darmin Avatar answered Jan 02 '23 19:01

Alexei Darmin


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:

  1. Include defaultOptions
  2. Add 2 members to your class that will store the resolve/reject methods for the promise.
  3. In your 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.
  4. Add an onFocus handler, and within it call the function to get your results, but also add .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.

like image 20
ErnestoP Avatar answered Jan 02 '23 20:01

ErnestoP


In order to load options when user focus first time, set defaultOptions={true}

like image 23
Gaurav Singh Avatar answered Jan 02 '23 20:01

Gaurav Singh