Author avatar

Gaurav Singhal

Process an API Response in React

Gaurav Singhal

  • Nov 17, 2020
  • 5 Min read
  • 118 Views
  • Nov 17, 2020
  • 5 Min read
  • 118 Views
Web Development
Front End Web Development
Client-side Frameworks
React

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:

1
npx create-react-app react-api-response
shell

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

1
npm i axios
shell

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.

1
import React,{useState} from 'react'; 
javascript

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

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

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.

1
2
3
useEffect(() => {
	fetchComments();
}, [])
javascript

Create the fetchComments() method, as shown below.

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

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:

1
2
3
useEffect(() => {
    console.log(comments)
}, [comments])
javascript

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 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>
  );
jsx

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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;
javascript

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.

0