Shiva Nara
Shiva Nara

Reputation: 81

Async Select in react not loading options

I am trying to load options for select field dynamically using React-Select. Here is my method that returns the loadOptions in Select.

 onChange(e)  {
    console.log("Value Printed : " + e);
 if(e.length > 3) {


 new Promise(resolve => {
    setTimeout(() => {           
    const url = `http://localhost:3010/cityNames?name=${e}`;
    fetch(url)
   .then(results => results.json())
   .then(data => {        
       var options = [];    
        options = data;
        console.log("return value from server: " + JSON.stringify(data));
        return {options: data};
   });
    }, 1000);
});

} else {console.log("Enter 3 chars");}
};

But my options aren't displaying.

Here is the render component.

   <AsyncSelect
    isClearable
    loadOptions={this.onChange}
    onInputChange={this.onChange}
   />

The console log shows the correct results. My data variable is:

 [{"label":"Dallas","value":680780}]

Upvotes: 3

Views: 3448

Answers (2)

Staz
Staz

Reputation: 151

added a key prop key={options.length} fixed my issue of not rendering options when options change later. Feel free to use this or similar as a fix as well.

 <AsyncSelect
    key={options.length}
    loadOptions={options}
   />

Upvotes: 2

kind user
kind user

Reputation: 41893

Apparently your component doesn't re-render when the data is fetched. Try to use state instead.

.then((data) => {      
    this.setState({ options: data });
});

And inside render:

<Select
   isClearable
   options={this.state.options}
   onInputChange={this.onChange}
/>

By the way, I really doubt that you have to use Async React Select. I think that the normal one would be enough, with a slight logic change.

Your code should look like:

onChange = (inputValue) => {
  if (inputValue.length > 3) {
      const url = `http://localhost:3010/cityNames?name=${inputValue}`;
        fetch(url)
          .then(results => results.json())
          .then(data => {
             this.setState({
                options: data,
             });
          });
    });
};

Upvotes: 0

Related Questions