Reputation: 463
I am using react-select for drop downs in my application. Below is my requirement.
Click in the text area of the second Select.
What is happening : I see No Options as the default drop down. I can see the values from the API only when I type something in the box and that matches the default filter criteria.
What I want to happen : It should display the values that we fetched from the API call.
const options = [{ label: "first", value: "first" }];
let options1 = [];
async function copyOptionsForAsync() {
let response = await fetch("https://jsonplaceholder.typicode.com/todos");
let data = await response.json();
data.forEach(element => {
let dropDownEle = { label: element["title"], value: element };
options1.push(dropDownEle);
});
}
class App extends React.Component {
constructor() {
super();
this.state = {
isSelected: false
};
}
handleOnchange = () => {
this.setState({ isSelected: true });
copyOptionsForAsync();
console.log(options1);
};
render() {
return (
<div className="App">
<Select
name="option"
options={options}
onChange={this.handleOnchange}
/>
{this.state.isSelected ? <App1 /> : null}
</div>
);
}
}
class App1 extends React.Component {
render() {
return (
<div className="App">
<Select name="options2" options={options1} />
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
This is the link to codesandbox page. Can any one tell me how will I be able to display the options once I click on the select box.
Upvotes: 2
Views: 11612
Reputation: 281
'App1' is rendering before you actually get the data. One way to fix this is to wait for the data to be fetched then render 'App1', like this:
handleOnchange = async () => {
await copyOptionsForAsync();
this.setState({ isSelected: true });
};
Working example in codesandbox: https://codesandbox.io/s/m6wr8zvjj
Upvotes: 2