Help with Initializing values in React

Here is my code

I’m writing the random quote machine using React and JQuery and it works fine when I click the new quote button but the method call in componentDidMount doesn’t seem to update the state of the quote and author fields.

Thanks in advance.

The loadQuotes function will not wait for the result of the ajax call before returning the array of quotes. Rather, it will return the empty array first.

You may want to set the quotes state inside the ajax callback. You will have to move the entire body of loadQuotes inside componentDidMount (but drop the return quotes line, then after the for-loop, call setState and setQuote. You’ll have to use an arrow function for the ajax callback, so the this in both functions still refer to the React component.

componentDidMount() {
  const quotes = [];
  // ...
  $.ajax({
    // ...
    success: (data) => {
      // variables...
      for (...) {
        // populate quotes array
      }
      this.setState(...);
      this.setQuote();
    }
  })
}
1 Like

I had the same reaction. I think he is only making an Ajax call, so no DOM manipulation through jQuery.

Yeah I suppose I can rewrite the get request without using jquery.