How to fetch data using Axios - Http Get Request in React Js?
In one of my previous post, I had explained all about Fetch() method to retrieve data from api server.
In this post, I am going to demystify how to achieve same thing using axios. Axios has many advantages over fetch() method.
1) Axios has the ability to intercept HTTP request.
2) With axios.all() method, you can make simultaneous requests, simply send an array of request to this method, then use axios.spread() method to assign the properties of the response array to separate varialbes.
3) Axios automatically stringifies the data when sending requests, as in fetch() method, you would have to do it manually.
4) You can set response timeout.
5) Support backward compatibility, this is because it uses XMLhttprequest under the hood.
|
Fetch User Data Using Axios - Get Request |
Installation:
npm install axios
or
yarn add axios
Sample Code:
A) index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
ReactDOM.render(<App />, document.getElementById("root"));
B) App.js
import React from "react";
import "./style.css";
import Users from './Users'
export default function App() {
return (
<div>
<Users />
</div>
);
}
C) Users.js
import React, { useState, useEffect } from 'react';
import './style.css';
import axios from 'axios';
function Users() {
const [userData, setUserData] = useState([]);
useEffect(() => {
axios
.get('https://jsonplaceholder.typicode.com/users')
.then((res) => {
setUserData(res.data);
})
.catch((err) => console.log(err));
}, []);
return (
<div>
<h1>Fetch User Data Using Axios - Get Request</h1>
<div id="divTable">
{userData.map((item) => (
<div id="divTableRow" key={item.id}>
<div id="divTableColumn">{item.username}</div>
<div id="divTableColumn">{item.name}</div>
<div id="divTableColumn">{item.email}</div>
</div>
))}
</div>
</div>
);
}
export default Users;
D) style.css
#divTable {
display: table;
width: auto;
background-color: #eee;
border: 1px solid #666666;
border-spacing: 5px;
}
#divTableRow {
display: table-row;
width: auto;
clear: both;
}
#divTableColumn {
float: left;
display: table-column;
width: 200px;
background-color: #ccc;
}
Happy Learning!! Happy Coding!!
Comments