Axios
Published: (January 15, 2026 at 04:06 AM EST)
2 min read
Source: Dev.to
Source: Dev.to

Axios Methods
| Method | Purpose |
|---|---|
axios.get() | Fetch data |
axios.post() | Create/submit data |
axios.put() | Update entire resource |
axios.patch() | Partial update |
axios.delete() | Delete data |
How to Use Axios in Your Projects
Step 1: Install Axios
npm install axios
# or
yarn add axios
Step 2: Basic Axios Usage
import axios from 'axios';
// GET request
axios.get('http://localhost:3000/api/users')
.then(response => console.log(response.data))
.catch(error => console.log(error));
// POST request
axios.post('http://localhost:3000/api/users', {
name: 'John',
email: 'john@example.com'
})
.then(response => console.log(response.data))
.catch(error => console.log(error));
// PUT request (update)
axios.put('http://localhost:3000/api/users/1', {
name: 'Jane'
})
.then(response => console.log(response.data))
.catch(error => console.log(error));
// DELETE request
axios.delete('http://localhost:3000/api/users/1')
.then(response => console.log(response.data))
.catch(error => console.log(error));
Step 3: In React Components (with Hooks)
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function UserList() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
// Fetch data on component mount
useEffect(() => {
fetchUsers();
}, []);
const fetchUsers = async () => {
setLoading(true);
try {
const response = await axios.get('http://localhost:3000/api/users');
setUsers(response.data.users);
setError(null);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
if (loading) return
Loading...
;
if (error) return
Error: {error}
;
return (
{users.map(user => (
### {user.name}
{user.email}
))}
);
}
export default UserList;
Step 4: With Authentication (Sending Tokens)
axios.post('http://localhost:3000/api/auth/login', {
email,
password
}, {
withCredentials: true, // Send cookies
headers: {
'Content-Type': 'application/json'
}
})
.then(response => console.log(response.data))
.catch(error => console.log(error));
Step 5: Create a Reusable Axios Instance
Create src/api/axiosInstance.js:
import axios from 'axios';
const axiosInstance = axios.create({
baseURL: 'http://localhost:3000/api',
withCredentials: true
});
// Add token to all requests
axiosInstance.interceptors.request.use(config => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
export default axiosInstance;
Use the instance in components:
import axiosInstance from '../api/axiosInstance';
// Instead of full URL
axiosInstance.post('/auth/login', { email, password })
.then(response => console.log(response.data))
.catch(error => console.log(error));