Axios: The “Fetch”ing Solution for Your React Needs
Have you ever been confused with fetch requests? Yes, it is a nightmare. Don’t worry, Axios is here to save you from that horrible finality.
Axios is a powerful tool that makes getting data from the web straightforward.
It’s an upgraded version of the built-in Fetch API, but it's cooler.
It performs all of the difficult tasks for you, such as converting data to JSON and resolving errors.
In this post, we’ll go over everything you need to know about Axios, from getting started to using it effectively.
You’ll be getting data like an expert in no time. Let’s go in!
We’ll learn how to:
- Get data
- Send data
- Fix errors when appear.
- And some smart Axios approaches.
Ready to learn Axios? Let’s get started.
Setting Up Axios
Okay, good. First, we need to add Axios to our project.
Just enter this into your terminal:
npm install axios
# or
yarn add axios
Okay, Axios is ready to go! Let’s add it to your project.
import axios from 'axios';
If you want to set up Axios globally (optional but very useful), you can build an Axios instance.
// Create a custom instance of Axios
const axiosInstance = axios.create({
// The base URL for all requests made with this instance
baseURL: 'https://api.example.com',
// The maximum amount of time (in milliseconds) to wait for a request before timing out
timeout: 1000,
// Custom headers to include with every request made using this instance
headers: {'X-Custom-Header': 'foobar'}
});
Axios in React
Axios makes it easy to send HTTP requests. Here is how to send GET, POST, PUT, and DELETE requests.
GET Request
// Sending a GET request to the server to retrieve data for a user with ID 12345
axios.get('/user?ID=12345')
.then(response => {
// If the request is successful, log the response data to the console
console.log(response.data);
})
.catch(error => {
// If there is an error with the request, log an error message to the console
console.error('There was an error!', error);
});
POST Request
// Making a POST request to the '/user' endpoint
axios.post('/user', {
firstName: 'Fred', // The data being sent in the request body
lastName: 'Flintstone' // This is the payload containing user details
})
.then(response => {
// This function executes if the request is successful
console.log(response.data); // Logs the response data from the server to the console
})
.catch(error => {
// This function executes if there's an error with the request
console.error('There was an error!', error); // Logs an error message and the error details to the console
});
PUT Request
// Make a PUT request to update user information
axios.put('/user/12345', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(response => {
// Handle success - log the response data to the console
console.log(response.data);
})
.catch(error => {
// Handle error - log the error message to the console
console.error('There was an error!', error);
});
DELETE Request
// Perform a DELETE request to remove a user with ID 12345
axios.delete('/user/12345')
.then(response => {
// Handle the successful response
// `response.data` contains the data returned from the server
console.log('User deleted successfully:', response.data);
})
.catch(error => {
// Handle any errors that occur during the request
console.error('There was an error deleting the user:', error);
});
Making GET Requests
Making GET requests with Axios is easy: but let’s go a bit more deeply.
axios.get('/users')
.then(response => {
// Set the state with the fetched user data
this.setState({ users: response.data });
})
.catch(error => {
// Log any errors that occur during the request
console.error('There was an error fetching the users!', error);
});
Best Practices
- Always handle both success and error scenarios.
- Update the state to reflect the fetched data.
- For carrying out the request on the component mount, use the
useEffect
property in functional components.
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const UsersList = () => {
// State to store users data
const [users, setUsers] = useState([]);
useEffect(() => {
// Function to fetch users data
const fetchUsers = async () => {
try {
const response = await axios.get('/users');
setUsers(response.data);
} catch (error) {
console.error('There was an error fetching the users!', error);
}
};
fetchUsers(); // Call the function to fetch data
}, []); // Empty dependency array means this runs once when the component mounts
return (
<div>
<h1>Users List</h1>
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
);
};
export default UsersList;
Making POST, PUT, and DELETE Requests
POST Request
// Function to add a new user
const addUser = (user) => {
// Sending a POST request to the '/users' endpoint with user data
axios.post('/users', user)
.then(response => {
// Log a success message and response data if the request is successful
console.log('User added!', response.data);
})
.catch(error => {
// Log an error message if there is an issue with the request
console.error('There was an error adding the user!', error);
});
};
PUT Request
// Function to update a user by their ID
const updateUser = (userId, updatedUser) => {
// Send a PUT request to update the user details
axios.put(`/users/${userId}`, updatedUser)
.then(response => {
// Log success message and updated user data to the console
console.log('User updated!', response.data);
})
.catch(error => {
// Log error message if the update fails
console.error('There was an error updating the user!', error);
});
};
DELETE Request
const deleteUser = (userId) => {
// Send a DELETE request to the server to remove the user with the specified ID
axios.delete(`/users/${userId}`)
.then(response => {
// Log a success message with the server's response data
console.log('User deleted!', response.data);
})
.catch(error => {
// Log an error message if the request fails
console.error('There was an error deleting the user!', error);
});
};
Error Handling
Error handling is essential to guaranteeing a positive user experience.
Using Try-Catch
// Import axios library (make sure you have axios installed and imported)
import axios from 'axios';
// Define an asynchronous function to fetch user data
async function fetchUserData() {
try {
// Make a GET request to the '/users' endpoint
const response = await axios.get('/users');
// Log the response data to the console
console.log(response.data);
} catch (error) {
// Handle any errors that occur during the request
console.error('There was an error fetching the user data!', error);
}
}
// Call the function to execute the request
fetchUserData();
Axios Interceptors
Interceptors let you carry out code or change the request/response before it gets sent or after it has been received.
axios.interceptors.response.use(
response => {
// This function is called for every successful response
return response;
},
error => {
// This function is called for every error response
console.error('Interceptor caught an error!', error);
// Reject the promise so the error can be handled elsewhere
return Promise.reject(error);
}
);
Creating a Custom Axios Instance
A custom Axios instance can improve and organize your requests.
// Create an Axios instance with custom configuration
const apiClient = axios.create({
// Set the base URL for all requests
baseURL: 'https://api.example.com',
// Set default headers for all requests
headers: {
'Content-Type': 'application/json' // Specifies that the request body format is JSON
}
});
Interceptors in Axios
Interceptors can change requests or responses on a global scale.
// Adding a request interceptor to the Axios instance
apiClient.interceptors.request.use(
config => {
// This function runs before each request is sent
console.log('Request made with ', config);
// Log the configuration of the request to the console
return config; // Ensure the request proceeds
},
error => {
// This function runs if there's an error with the request
return Promise.reject(error); // Reject the promise to handle the error
}
);
// Setting up an Axios interceptor for handling responses
apiClient.interceptors.response.use(
response => {
// Log the response to the console for debugging purposes
console.log('Response received:', response);
// Return the response to allow the promise chain to continue
return response;
},
error => {
// Handle errors by rejecting the promise
// This will allow you to catch errors in your request logic
return Promise.reject(error);
}
);
Axios with Async/Await
Async/await can help to clean up and improve the accessibility of your code.
// Define an asynchronous function to fetch user data
const fetchUsers = async () => {
try {
// Make a GET request to the '/users' endpoint
const response = await apiClient.get('/users');
// Log the response data to the console
console.log(response.data);
} catch (error) {
// Handle any errors that occur during the request
console.error('There was an error fetching the users!', error);
}
};
Axios with React Hooks
Using Axios with React hooks is a game changer.
Here’s how to fetch data in a functional component.
import React, { useState, useEffect } from 'react';
import axios from 'axios';
// Functional component to display a list of users
const UsersList = () => {
// State to hold the list of users
const [users, setUsers] = useState([]);
// useEffect hook to fetch users when the component mounts
useEffect(() => {
// Async function to fetch users from the API
const fetchUsers = async () => {
try {
// Make a GET request to the /users endpoint
const response = await axios.get('/users');
// Update state with the fetched users
setUsers(response.data);
} catch (error) {
// Log any error that occurs during the fetch
console.error('There was an error fetching the users!', error);
}
};
// Call the fetchUsers function
fetchUsers();
}, []); // Empty dependency array means this runs once after the initial render
return (
<div>
{/* Render a list of user names */}
{users.map(user => (
<div key={user.id}>{user.name}</div>
))}
</div>
);
};
export default UsersList;
Best Practices
- Always handle errors and clean up resources.
- Use caching methods as needed.
- Avoid sharing important details in requests.
- Use a custom Axios instance to keep environments consistent.
Troubleshooting Common Issues
- CORS Errors: Ensure that your server supports cross-origin requests.
- Timeouts: Configure your Axios timeout settings depending on your needs.
- Network Errors: Check your network connection and API endpoint.
Conclusion
This detailed guide covers using Axios with ReactJS. I have covered everything, from basic setup to advanced usage. Now make those HTTP requests like an expert! And be sure to follow me for more.