YouTube Icon

Code Playground.

How to Process an API Response in React

CFG

How to Process an API Response in React

Introduction

Working with backend administrations, for example, a REST API is perhaps the most well-known errand of a frontend engineer. Regardless React application you're working, sooner or later, you'll most likely need to make a solicitation to a data set server or an endpoint and snatch an information to show to the client. For example, assuming you're fabricating a web-based entertainment application and you need to show remarks on a specific post to the client, you want to make a solicitation to a devoted API to get every one of the remarks and afterward process it further in your application.

In this aide, you'll figure out how to call an API to bring its reaction in your React application.

Beginning Setup

How about we go through a guide to get a superior comprehension of how you can call the API reaction. Make a void React application by running:

npx create-react-app react-api-response

Then, introduce the Axios library. Axios is a library that improves on the most common way of collaborating with APIs.

npm i axios

The endpoint you will use in this model is https://jsonplaceholder.typicode.com/remarks. A free REST API endpoint returns a few sham information you can mess with. You can pick some other such API or utilize your own API also.

Making State to Store Response

Anything reaction you get from an API, you really want to store it locally inside that part so you can deal with it further. Import the useState snare from React to make a piece of state to store the reaction.

import React,{useState} from 'react'; 

Make a state variable remarks and a snare to set the worth of this state variable setComments utilizing the useState snare.

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

Since the remarks returned will be a variety of items with each article addressing a solitary remark, the underlying worth of remarks is a vacant cluster.

Calling API and Processing Response

Ordinarily, you need to bring information inside a part when its whole DOM loads. All in all, when your App part first mounts on the DOM, you want to make a solicitation to the API. In React, this can be done by means of a part lifecycle strategy called componentDidMount(), which is terminated when the part first loads on the DOM. A basic snares execution can be done by terminating an offbeat capacity utilizing the async catchphrase inside useEffect() and passing an unfilled cluster as a boundary, as displayed underneath.

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

Make the fetchComments() strategy, as displayed underneath.

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

Inside fetchComments(), consider the API by passing the endpoint to Axios and store the reaction in a variable utilizing the anticipate watchword. Every one of the remarks from the endpoint can be alluded to by calling the information property on the reaction object to set the state. You can check in the event that you accurately attached remarks to your state utilizing the accompanying piece of code:

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

Yielding Response on the DOM

Such a long ways in this aide, you have called the API reaction and put away it inside your state. You can deal with it further utilizing the state. For example, you can spin through the remarks and render each remark on the DOM, as displayed beneath.

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

Examine the whole App part, which calls the API on mounting, sets the reaction to the part's state, and results 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://xyz.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 cooperate with an API in various ways by making various types of solicitations from your application. For example, you can make a POST solicitation to add another remark by putting away it in the information base. Be that as it may, to handle any unique information from a server on stacking a part, you ought to make demands in componentDidMount() and store them inside your state, as illustrated. Rather than essentially yielding this information, you can investigate more choices, for example, sifting or arranging information, adding pagination, and so on.




CFG