Whenever you need to get the data from the backend using an API the GET API request call comes into rescue. In our other articles we have shared information about DELETE API Call, PUT API Call and POST API Call you can read those to get more knowledge around the CRUD Operations.
Table of Contents
Axios Installation & Import in React JS
Installation
With NPM: npm install axios
With Yarn: yarn add axios
Import
import axios from “axios”;
How to make a GET Requests with AXIOS (Retrieve/GET API Call)
Axios provide us a function called axios.get() that helps in retrieving the data from the backend with an HTTP GET request.
GET API Call in Function-Based Component
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function EmployeeList() {
const [employees, setEmployees] = useState([]);
useEffect(() => {
axios.get(`http://dummy.restapiexample.com/api/v1/employees`)
.then(response => {
setEmployees(response.data)
});
}, []);
return (
<>
<h4>Axios Get Request Example in React</h4>
<table classname="table table-bordered">
<tr>
<th>ID</th>
<th>Name</th>
<th>Salary</th>
<th>Age</th>
</tr>
{employees && employees.map((emp) => (
<tr>
<td>{emp.id}</td>
<td>{emp.employee_name}</td>
<td>{emp.employee_salary}</td>
<td>{emp.employee_age}</td>
</tr>
))}
</table>
</>
);
}
GET API Call in Class-Based Component
import React from 'react';
import axios from 'axios';
export default class EmployeeList extends React.Component {
state = {
employees: []
}
componentDidMount() {
axios.get(`http://dummy.restapiexample.com/api/v1/employees`)
.then(response => {
this.setState({ employees: response.data });
})
}
render() {
const { employees } = this.state;
return (
<>
<h4>Axios GET Request Example in React</h4>
<table classname="table table-bordered">
<tr>
<th>ID</th>
<th>Name</th>
<th>Salary</th>
<th>Age</th>
</tr>
{employees && employees.map((emp) => (
<tr>
<td>{emp.id}</td>
<td>{emp.employee_name}</td>
<td>{emp.employee_salary}</td>
<td>{emp.employee_age}</td>
</tr>
))}
</table>
</>
)
}
}
More Information
In the previous blog about “PUT API Call” we have shared more information for handling api errors, adding Headers and making calling API with Axios API and have also shared details about making it more readable and synchronized with Async-Await.
Hope you have seen other articles related to Axios. Great learning.
2 thoughts on “Call API – GET Requests with AXIOS | React JS”