Making API calls in ReactJS using Fetch

Author Purushothaman Raju ,Posted on June 02 2020

Integrating an API in React is one of the key skills one should know while learning React or any other frontend libraries like Vue or AngularJS. We will be seeing the Fetch API which is available across major browsers.

There are certain browsers like IE9 which do not support the Fetch completely but there are workarounds to fix it. The Fetch API supports most of the HTTP methods like GET, POST, PUT, and DELETE. let us see an example of how we can make an API call using fetch.

Let us create a class component in React and add our fetch API call inside the componentDidMount lifecycle method and store the response in the component state.

We will be using jsonplaceholder.typicode.com as our API endpoint this is a free service, feel free to use this service in your react learning projects.

import React from "react";

class MyApp extends React.Component {
  state = {
    data: null,
  };

  componentDidMount() {
    fetch("https://jsonplaceholder.typicode.com/posts")
      .then((res) => res.json())
      .then((response) => {
        this.setState({ data: response });
      })
      .catch((err) => console.log(err));
  }

  render() {
    if (!this.state.data) {
      return null;
    }

    return (
      <div>
        {this.state.data.map((post) => {
          return (
            <div key={post.id}>
              <h3>{post.title}</h3>
              <p>{post.body}</p>
            </div>
          );
        })}
      </div>
    );
  }
}

export default MyApp;


Notice the use of .then() function we use this because by default fetch will return a promise as in fetch is asynchronous. The .then() method is chained to the fetch call and will be invoked once we have a response from the API. Once we have the response we store that in the state and use the map function to loop through all post items and show it on the browser.

The above example is for a GET method. If you want to use the POST method where you might want to send some data to a server. The fetch API provides the body and header properties to send data. see the code snippet below to know how to send data via the POST method in Fetch.

fetch('http://myapiendpoint.com',{
	method:'POST',
	headers:{
	 'Content-Type':'application/json',
	 'Authorization':'Bearer mytoken1233434343423232'
	},
	body:{"todoTitle":"Learn React"}
});

Hope you find this article useful on Fetch API.