Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Process an API Response in React

No matter what React app you're building, at some point, you'll probably want to make a request to a database server or an *endpoint* and grab some data to display to the user.

Nov 17, 2020 • 5 Minute Read

Introduction

Working with backend services such as a REST API is one of the most common tasks of a frontend developer. No matter what React app you're building, at some point, you'll probably want to make a request to a database server or an endpoint and grab some data to display to the user. For instance, if you're building a social media app and you want to display comments on a certain post to the user, you need to make a request to a dedicated API to fetch all the comments and then process it further in your app.

In this guide, you'll learn how to call an API to fetch its response in your React app.

Initial Setup

Let's run through an example to get a better understanding of how you can call the API response. Create an empty React app by running:

      npx create-react-app react-api-response
    

Next, install the Axios library. Axios is a library that simplifies the process of interacting with APIs.

      npm i axios
    

The endpoint you're going to use in this example is https://jsonplaceholder.typicode.com/comments. It's a free REST API endpoint that returns some dummy data you can play around with. You can choose any other such API or use your own API as well.

Creating State to Store Response

Whatever response you get from an API, you need to store it locally within that component so you can process it further. Import the useState hook from React to create a piece of state to store the response.

      import React,{useState} from 'react';
    

Create a state variable comments and a hook to set the value of this state variable setComments using the useState hook.

      const [comments,setComments]=useState([])
    

Since the comments returned will be an array of objects with each object representing a single comment, the initial value of comments is an empty array.

Calling API and Processing Response

Usually, you want to fetch data inside a component when its entire DOM loads. In other words, when your App component first mounts on the DOM, you need to make a request to the API. In React, this can be carried out via a component lifecycle method called componentDidMount(), which is fired when the component first loads on the DOM. A simple hooks implementation can be carried out by firing an asynchronous function using the async keyword inside useEffect() and passing an empty array as a parameter, as shown below.

      useEffect(() => {
	fetchComments();
}, [])
    

Create the fetchComments() method, as shown below.

      const fetchComments=async()=>{
    const response=await Axios('https://jsonplaceholder.typicode.com/comments');
    setComments(response.data)    
}
    

Inside fetchComments(), call the API by passing the endpoint to Axios and store the response in a variable using the await keyword. All the comments from the endpoint can be referred to by calling the data property on the response object to set the state. You can check if you correctly appended comments to your state using the following piece of code:

      useEffect(() => {
    console.log(comments)
}, [comments])
    

Outputting Response on the DOM

So far in this guide, you have called the API response and stored it inside your state. You can process it further using the state. For instance, you can cycle through the comments and render each comment on the DOM, as shown below.

      return (
    <div className="App">
      {
        comments && comments.map(comment=>{
          return(
            <div key={comment.id} style={{alignItems:'center',margin:'20px 60px'}}>
            <h4>{comment.name}</h4>
            <p>{comment.email}</p>
          </div>
          )

        })
      }
     
    </div>
  );
    

Have a look at the entire App component, which calls the API on mounting, sets the response to the component's state, and outputs it on the DOM.

      import './App.css';
import Axios from 'axios'
import React,{useState,useEffect} from 'react';

function App() {
  const [comments,setComments]=useState([])
  useEffect(() => {
    fetchComments();
  }, [])
  useEffect(() => {
    console.log(comments)
  }, [comments])
  const fetchComments=async()=>{
    const response=await Axios('https://jsonplaceholder.typicode.com/comments');
    setComments(response.data)    
  }
  return (
    <div className="App">
      {
        comments && comments.map(comment=>{
          return(
            <div key={comment.id} style={{alignItems:'center',margin:'20px 60px'}}>
            <h4>{comment.name}</h4>
            <p>{comment.email}</p>
          </div>
          )

        })
      }
    </div>
  );
}

export default App;
    

Conclusion

You can interact with an API in different ways by making different kinds of requests from your app. For instance, you can make a POST request to add a new comment by storing it in the database. However, to process any dynamic data from a server on loading a component, you should make requests in componentDidMount() and store them inside your state, as demonstrated. Instead of simply outputting this data, you can explore more options, such as filtering or sorting data, adding pagination, etc.

Gaurav Singhal

Gaurav S.

Guarav is a Data Scientist with a strong background in computer science and mathematics. He has extensive research experience in data structures, statistical data analysis, and mathematical modeling. With a solid background in Web development he works with Python, JAVA, Django, HTML, Struts, Hibernate, Vaadin, Web Scrapping, Angular, and React. His data science skills include Python, Matplotlib, Tensorflows, Pandas, Numpy, Keras, CNN, ANN, NLP, Recommenders, Predictive analysis. He has built systems that have used both basic machine learning algorithms and complex deep neural network. He has worked in many data science projects, some of them are product recommendation, user sentiments, twitter bots, information retrieval, predictive analysis, data mining, image segmentation, SVMs, RandomForest etc.

More about this author