Rest API- React And AXIOS In Functional Component | Assign Axios Response To Function Component State


 This article will discuss correctly how to assign Axios response to react function component state and also will discuss how we can use Rest API React and AXIOS in the functional component.

we will parse Rest API responses with JSON using AXIOS in the functional component and then we will bind that data in an HTML table.

For that, you need to Make the Axios request inside the useEffect hook, in order to execute once the component is mounted.

Get data from Axios and return it from a Function Component in React

Dynamic data from API, i. e a request with Axios should be done within a useEffect hook, With the dependencies array empty []. so that the request in the useEffect hook will only happen in the first render. and when the response is received, store the result in a state and then Render the data based on the value of the state.

AXIOS in functional component

I have used the below API for showing you the example.

1.GET http://samplerestapi.com/api/Metadata/GetEmployees

Response Body

[
  {
"Id": 1,
"Name": "Pascale Cartrain",
"Address": "Rua do Mercado, 12",
"City": "Walla",
"ZipCode": "243232"
  },
  {
"Id": 2,
"Name": "Liu Wong",
"Address": "DaVinci",
"City": "Paris",
"ZipCode": "243232"
  },
  {
"Id": 3,
"Name": "Miguel",
"Address": "Avda. Azteca",
"City": "London",
"ZipCode": "243232"
  },
  {
"Id": 4,
"Name": "Anabela",
"Address": "ul. Filtrowa 68",
"City": "Florida",
"ZipCode": "243232"
  },
  {
"Id": 5,
"Name": "Mary Saveley",
"Address": "Adenauerallee",
"City": "Tokyo",
"ZipCode": "243232"
  },
  {
"Id": 6,
"Name": "Nik",
"Address": "DaVinci",
"City": "Tokyo",
"ZipCode": "2445432"
  },
  {
"Id": 7,
"Name": "Johny",
"Address": "Azteca",
"City": "London",
"ZipCode": "67643"
  }
]

Employeelist.js

 

import React, { useState, useEffect } from "react"
import axios from 'axios';


const Employeelist = () => {
const [employeeslist, setemployees] = useState(null)
    useEffect(() => {
        getemployees()
    }, [])
const getemployees = () => {
            axios.get('http://samplerestapi.com/api/Metadata/GetEmployees').then(response => response.data).then(
                (result) => {
                    setemployees(result)
                },
                (error) => {
                    setemployees(null);
                }
              )
    }
if (!employeeslist) return (<div>No Record Found</div>)
return (<div>
        <h2>Fetch Employees List inside Funcational Component using axios</h2>
        <table className="table" >
            <thead>
                <tr>
                    <th>Employee Id</th>
                    <th>Name</th>
                    <th>Address</th>
                    <th>City</th>
                    <th>ZipCode</th>
                </tr>
            </thead>
            <tbody>
                {employeeslist.map(emp => (
                    <tr key={emp.Id}>
                        <td>{emp.Id}</td>
                        <td>{emp.Name}</td>
                        <td>{emp.Address}</td>
                        <td>{emp.City}</td>
                        <td>{emp.ZipCode}</td>
                    </tr>
                ))}
            </tbody>
        </table>
    </div>)
}
export default Employeelist;


Employeelist that fetches data from a REST API using Axios and displays it in a table format. 

useState, useEffect: Hooks from React for managing component state and performing side effects respectively.axios: Library for making HTTP requests.

Employeelist Component: It initializes a state variable employeeslist 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 getemployees function when the component mounts ([] as dependency).

The getemployees function makes a GET request to the specified API endpoint using Axios.
Upon receiving the response, it updates the employeeslist state with the fetched data.
If an error occurs during the fetch operation, it sets the employeeslist state to null.

The fetched data is mapped over and displayed row by row in the <tbody> section of the table.
Each row displays the employee's ID, name, address, city, and zip code.
Conditional Rendering:

If employeeslist state is null (indicating no data fetched), it renders a message "No Record Found" within a <div>.

So using above code you can effectively fetches data from the specified API endpoint using Axios and dynamically renders it in a tabular format on the UI.

In ReactJS, Axios is a library that effectively makes HTTP demands that are available remotely. It is clear from the way that we may at times in React applications need to get information from the outer source. It is very hard to get such information so they can be typically displayed on the site. Along these lines, it helps in recovering the information accordingly adding it to the state to work with the application at whatever point the necessity emerges.

Moreover, respond Axios is extremely simple to adjust and is very lightweight. It likewise works perfectly with numerous different structures present today. The principal reason for utilizing Axios is to get support for solicitation and reaction capture attempt, change of information into JSON design, and change it. It additionally helps you in safeguarding XSRF fraud naturally while you demand cross-site access.

Axios is guarantee based, which empowers you to exploit JavaScript’s async and anticipate for more lucid offbeat code.

It allows you to utilize offbeat lucid code present in Javascript. It very well may be handily used to drop or block demands with the assistance of the in-assembled element of client-side insurance of fabrication across the cross-site demand.