Fetch And Display Data From API In React JS Using Axios


If you are new to Reactjs and looking to enhance your skills with a test project, especially in calling and fetching data from a REST API using Axios, then you've come to the right place.

In this project, we'll establish a structure where the UI component connects to a REST API and utilizes the returned data. While there are many examples of this concept available on the internet, this article will specifically focus on implementing it using Axios.

For showing you an example I’m using the below example API for getting the data.

1.GET http://samplerestapi.com/api/TravelAgent

Json Response

[
{
"id": 122409,
"agent_name": "Mike",
"agent_email": "[email protected]",
"agent_location": "Paris",
"createdat": "2022-05-20T07:15:59.7729513"
},
{
"id": 122408,
"agent_name": "Mike",
"agent_email": "[email protected]",
"agent_location": "Paris",
"createdat": "2022-05-20T07:13:06.7843333"
},
{
"id": 122407,
"agent_name": "KartikBandi",
"agent_email": "[email protected]",
"agent_location": "Armoor",
"createdat": "2022-05-20T07:08:22.5717523"
},
{
"id": 122391,
"agent_name": "guruswamy",
"agent_email": "[email protected]",
"agent_location": "india",
"createdat": "2022-05-20T05:32:35.1775134"
},
{
"id": 122389,
"agent_name": "sdsd",
"agent_email": "[email protected]",
"agent_location": "sdsd",
"createdat": "2022-05-20T05:27:51.8326946"
},
{
"id": 122388,
"agent_name": "dhiraj shende",
"agent_email": "[email protected]",
"agent_location": "IND",
"createdat": "2022-05-20T05:27:40.5961154"
},
{
"id": 122387,
"agent_name": "yashwitha",
"agent_email": "[email protected]",
"agent_location": "US",
"createdat": "2022-05-20T05:11:38.4162423"
},
{
"id": 122079,
"agent_name": "rupal",
"agent_email": "[email protected]",
"agent_location": "india23232",
"createdat": "2022-05-19T13:10:26.8226353"
},
{
"id": 122078,
"agent_name": "abhishek",
"agent_email": "[email protected]",
"agent_location": "india",
"createdat": "2022-05-19T13:07:22.3235079"
},
{
"id": 122077,
"agent_name": "mahendra",
"agent_email": "[email protected]",
"agent_location": "rRatlam",
"createdat": "2022-05-19T13:05:09.2087452"
},
{
"id": 122076,
"agent_name": "Dnady",
"agent_email": "[email protected]",
"agent_location": "iNdoneisa",
"createdat": "2022-05-19T13:03:27.5413588"
},
{
"id": 122074,
"agent_name": "dhiraj shende",
"agent_email": "[email protected]",
"agent_location": "IND",
"createdat": "2022-05-19T13:01:08.7516211"
},
{
"id": 122072,
"agent_name": "Elif Sinano?lu",
"agent_email": "[email protected]",
"agent_location": "Bart?n",
"createdat": "2022-05-19T12:57:33.6831017"
},
{
"id": 122069,
"agent_name": "Ilija Milanoski",
"agent_email": "${RndEmail}.com",
"agent_location": "Vigo",
"createdat": "2022-05-19T12:56:56.2610036"
},
{
"id": 122068,
"agent_name": "Jesus Benitez",
"agent_email": "[email protected]",
"agent_location": "Vigo",
"createdat": "2022-05-19T12:56:55.8662293"
},
{
"id": 122064,
"agent_name": "Cecilie Wojcik",
"agent_email": "[email protected]",
"agent_location": "Bud",
"createdat": "2022-05-19T12:56:14.4489244"
},
{
"id": 122061,
"agent_name": "Xavier Ross",
"agent_email": "[email protected]",
"agent_location": "Keswick",
"createdat": "2022-05-19T12:55:41.3629308"
},
{
"id": 122056,
"agent_name": "Ilija Milanoski",
"agent_email": "[email protected]",
"agent_location": "Van",
"createdat": "2022-05-19T12:55:12.2889649"
},
{
"id": 122019,
"agent_name": "nimisha",
"agent_email": "n",
"agent_location": "USA",
"createdat": "2022-05-19T12:36:12.6214081"
},
{
"id": 122015,
"agent_name": "dhiraj shende",
"agent_email": "[email protected]",
"agent_location": "IND",
"createdat": "2022-05-19T12:22:19.3782778"
}
]

If you are looking for a sample rest for testing purposes then visit here, in this article I have listed a sample test API for testing purposes.

For that, I created a FetchDataFn.js file, that is the UI component, and for API calls, using Axios.we are going to Fetch and display data in a table using bootstrap from API in React JS using Axios.

Step 1. Install Axios library in our project

npm install axios –save axios

Step 2.Install bootstrap in our project for using bootstrap table.

npm install react-bootstrap bootstrap

Step 3:Write code

Fetch and display data from API in React JS using Axios

Axios React functional component

FetchDataFn.js

import React, { useState, useEffect } from "react"
import axios from 'axios';
import { Table, Button } from 'react-bootstrap';

const FetchDataFn = () => {
const [agents, setagent] = useState(null)
    useEffect(() => {
        getagents()
    }, [])
const getagents = () => {
            axios.get('http://samplerestapi.com/api/TravelAgent').then(response => response.data).then(
                (result) => {
                    setagent(result)
                },
                (error) => {
                    setagent(null);
                }
              )
    }
if (!agents) return (<div>No Record Found</div>)
return (
    <div>
        <h2>Fetch data in Funcational Component </h2>
        <Table className='table'>
            <thead className="btn-primary">
              <tr>
                <th>First Name</th>
                <th>EmailId</th>
                <th>Address</th>
                <th>CreatedAt</th>
                
              </tr>
            </thead>
            <tbody>
              {agents.map(agent => (
                <tr key={agent.id}>
                  <td>{agent.agent_name}</td>
                  <td>{agent.agent_email}</td>
                  <td>{agent.agent_location}</td>
                  <td>{agent.createdat}</td>
                </tr>
              ))}
            </tbody>
          </Table>
    </div>
    
    )
}
export default FetchDataFn;

 

Fetches data from a REST API using Axios and displays it in a table format. Let's break down the code:

useState, useEffect: Hooks from React for managing component state and performing side effects respectively.

axios: Library for making HTTP requests.Components from the react-bootstrap library for styling the UI.It initializes a state variable agents using the useState hook, which will hold the fetched data.

The useEffect hook is used to perform side effects in function components. In this case, it calls the getagents function when the component mounts ([] as dependency).Upon receiving the response, it updates the agents state with the fetched data.If an error occurs during the fetch operation, it sets the agents state to null.The component returns JSX to render the fetched data.

Overall, FetchDataFn component efficiently fetches data from the specified API endpoint and dynamically renders it in a tabular format on the UI.

Axios React class component

if you are looking for example  Fetch and display data from API in React JS using Axios in class component then look at below example.

import { Table, Button } from 'react-bootstrap';
import axios from 'axios';
import React from 'react';

const apiUrl = 'http://samplerestapi.com';

class FetchData extends React.Component {
  constructor(props) {
    super(props);
this.state = {
      error: null,
      agents: [],
      response: {}
    }
  }

  componentDidMount() {
    axios.get(apiUrl + '/api/TravelAgent').then(response => response.data).then(
      (result) => {
this.setState({
          agents: result
        });
      },
      (error) => {
this.setState({ error });
      }
    )
  }
  
  render() {
const { error, agents } = this.state;
if (error) {
return (
        <div>Error:{error.message}</div>
      )
    }
else {
return (
        <div>

          <Table className='table'>
            <thead className="btn-primary">
              <tr>
                <th>First Name</th>
                <th>EmailId</th>
                <th>Address</th>
                <th>CreatedAt</th>
                
              </tr>
            </thead>
            <tbody>
              {agents.map(agent => (
                <tr key={agent.id}>
                  <td>{agent.agent_name}</td>
                  <td>{agent.agent_email}</td>
                  <td>{agent.agent_location}</td>
                  <td>{agent.createdat}</td>
                </tr>
              ))}
            </tbody>
          </Table>
        </div>
      )
    }
  }
}

export default FetchData;  

While managing web applications in React, the most widely recognized task is to speak with backend servers. This is normally done through HTTP convention.

We are intimately acquainted with the exceptionally normal XML Http Request connection point and Fetch API, which permits us to bring information and make HTTP demands.

There is one more method for speaking with the backend in React, and in this article we will find out about the wonderful library known as Axios and a portion of the critical elements of Axios that have added to its prominence among frontend designers.

So we should get everything rolling.

What is Axios? (A tad of history)
Axios is utilized to speak with the backend and it additionally upholds the Promise API that is local to JS ES6.
It is a library which is utilized to make solicitations to an API, return information from the API, and afterward get things done with that information in our React application.
Axios is an extremely famous HTTP client, which permits us to make HTTP demands from the program.
For what reason Do We Need Axios in React?
Axios permits us to speak with APIs effectively in our React applications. However this can likewise be accomplished by different techniques like get or AJAX, Axios can give a tiny amount of greater usefulness that makes a remarkable difference with applications that utilization React.

Axios is a guarantee based library utilized with Node.js and your program to make nonconcurrent JavaScript HTTP demands.

Whenever we realize we want to execute some guarantee based nonconcurrent HTTP demands in our application, with JavaScript, we normally consider just jQuery’s AJAX or get strategy to take care of business. And keeping in mind that doing as such, we are really conflicting with React!! Did you see that?