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 = [];
  // ...
    // ...
    success: (data) => {
      // variables...
      for (...) {
        // populate quotes array
1 Like

What is the main purpose of using jQuery which you can not accomplish in React? These are two completely different libraries. jQuery manipulates the DOM directly and React relies on a virtual DOM. jQuery could easily cause unexpected results, if you start manipulating the DOM outside of React.

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

In the case, why not use the JavaScript built-in fetch or maybe a lightweight library like axios.js which are designed exclusively for requesting data from other servers.

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