3

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}]
0

2 Answers 2

3

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}
   />
Sign up to request clarification or add additional context in comments.

Comments

0

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,
             });
          });
    });
};

8 Comments

Well, it is not giving any errors in console, neither it shows the options on browser.
The console.log shows the values I am getting from the backend, but just it doesnt display
Here is the data variable again. [{"label":"Dallas","value":680780}]
@ShivaNara Replace your async select with normal react select and it should be fine
But when I clear my text and enter a new text, it is not fetching the new results?
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.