Sachin Kumar
Sachin Kumar

Reputation: 463

how to populate options for a react select by fetching values from an api to be visible when you click on the select box?

I am using react-select for drop downs in my application. Below is my requirement.

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

Answers (1)

Robert Purcea
Robert Purcea

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

Related Questions