xiety
xiety

Reputation: 284

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

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

Upvotes: 8

Views: 11761

Answers (4)

Gaurav Singh
Gaurav Singh

Reputation: 41

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

Upvotes: 2

Perestrelo
Perestrelo

Reputation: 233

Thanks, Alexei Darmin for the solution, I was struggling with this... while testing it I converted the solution to a react functional component and added real API fetching.

Here is a working demo, I hope it helps someone

Upvotes: 0

ErnestoP
ErnestoP

Reputation: 93

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.

Upvotes: 1

Alexei Darmin
Alexei Darmin

Reputation: 2129

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.

Upvotes: 13

Related Questions