Axios - Promise-based HTTP client
Ayush Kumar
1 min read
Step 1: Install Axios
npm install axios
Step 2: Setting Up Axios Instance (Optional)
// ๐ /src/utils/axios.jsx
import axios from "axios";
const instance = axios.create({
baseURL: "https://jsonplaceholder.typicode.com/",
timeout: 10000, // Optional: Set a timeout for requests
headers: {
'Content-Type': 'application/json', // Set default headers
},
})
export default instance;
// https://jsonplaceholder.typicode.com/users
// https -> protocol
// jsonplaceholder -> domaain/name
// typicode.com -> subdomain
// /users -> endpoint/route
step 3: Using Axios Instance:
import React, { useEffect, useState } from 'react'
// import axios from 'axios'
import axios from "../utils/axios"; // Using Axios Instance:
const Users = () => {
const [users, setUsers] = useState([]);
const getUser = async () => {
try {
// const response = await axios.get('https://jsonplaceholder.typicode.com/users')
const response = await axios.get('/users')
console.log(response.data);
setUsers(response.data);
} catch (error) {
console.error(error)
}
}
useEffect(() => {
getUser();
return () => {
console.log("Component Unmounted");
}
}, [])
return (
<div className='container '>
{users.map((user) => {
return <li key={user.id} className='list-user' >{user.name}</li>
})}
</div>
)
}
export default Users
0
Subscribe to my newsletter
Read articles from Ayush Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Ayush Kumar
Ayush Kumar
A passionate MERN Stack Developer from India I am a full stack web developer with experience in building responsive websites and applications using JavaScript frameworks like ReactJS, NodeJs, Express etc.,