JavaScript – fetch api data is run too late

I am fetching data from api to pass it as array to Select’s options. The problem is that data is fetched too late. My constructor():

constructor(props) {
    super(props);
    this.state = {
      optionSelected: null,
      options: []
    };
  }

My componentDidMount():

componentDidMount() {
    fetch('/authors/')
      .then(response => response.json())
      .then(data => {
        for (var x in data) {
          this.state.options.push({"value": x, "label": data[x]})
        }
      })
  ;}

With code like that I get empty drop down, with only "select all" option available.
But when I choose that "select all", drop down options are instantly populated with api data and all are selected. If I unselect all of them they remain as avaialble options. Can you please advice how can I make fetch populate options earlier then this so they were shown as select options from the very beggining?

Leave a Comment