Help with Initializing values in React

Help with Initializing values in React
0

#1

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.


#2

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();
    }
  })
}

#3

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.


#4

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


#5

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.

https://www.npmjs.com/package/axios

https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js


#6

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