Random Quote Machine: Fetch Data from an API in ReactJS

Hi everyone, I’m working on the Ramdom Quote Machine Project and I’m stucking on getting data from an API. Does anyone know how to do that in ReactJS? Could we use jQuery along with React? Please help me! :slight_smile: :slight_smile:

You load the data in a lifecycle callback, so generally you will have your component class, with empty state for the data, then you define the componentDidMount() method, in which you fetch data from the API and set it in the state. Something like:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      myApiData: []
    };
  }
  
  componentDidMount() {
    fetch('https://example.api.com')
    .then(response => response.json())
    .then(data => this.setState({myApiData: data});
  }

  render() {
    // rendering stuff here
  }
}

You absolutely don’t need jQuery to make AJAX requests, it’s already built into the browser API:

If you really want to use a library, then use one that specifically for HTTP requests (eg Axios), bringing in jQuery just so you can use a single one of its functions is pointless

2 Likes

Thank you very much for your help! I am now able to fetch data without using jQuery :smiley: But I have another question which seems to be a little bit off-topic. Could you tell me why the console log the empty array before the one filled with data? Here are the code and the console capture:


2

1 Like

setState is asynchronous, just like fetch or $.getJSON. So, calling the function doesn’t mean it’s done anything just yet. In order to see the updates, change your code thusly:

fetch(API_LINK)
    .then(response => response.json())
    .then(data => this.setState({quotesData: data.quotes }, () => console.log(this.state.quotesData));

Notice that setState takes a callback that fires after it updates the state. Asynchronous code is a big, important topic, so I suggest getting some exposure to it. Here are some videos:

https://www.youtube.com/results?search_query=asynchronous+javascript

1 Like

Thank you very much! I will definitely take a look at the video :smiley: