Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
You all must be familiar with React. Today we will be discussing Axios in React. Axios is a popular library used for making HTTP requests in JavaScript, and it can be used in a React application. This article will cover the installation of Axios, types of requests, error handling, etc.
This article is going to be a very informative one. You will be learning lots of concepts. So let's begin by first learning about React.
ReactJS is a JavaScript library for building user interfaces, particularly web applications with complex and interactive UIs. It was developed by Meta (previously Facebook), and it is widely used for building complex, high-performance web applications. React provides reusable UI components. It uses a virtual DOM to optimize updates and improves overall performance.
React became famous because of its excellent community support, flexibility, improved efficiency, simplicity, and reusable components. Many companies use React for their products.
What is Axios?
Axios is a popular, promise-based JavaScript library that is used for making HTTP requests. It returns a promise that is either resolved or rejected based on the outcome of the request.
It has the ability to easily handle JSON data and can make different types of requests like GET, and POST requests. It is just like the built-in fetch() function.
Now let's see how to start using Axios.
Installation of Axios
There are multiple ways to include Axios in your project. You can install it using any of the following methods.
Once it is installed, you can import it into your React component and start using it. Simply write the following statement to import it.
import axios from 'axios';
Making Requests with Axios
Axios handles request methods such as GET, POST, DELETE, PUT, HEAD, OPTIONS, PATCH, etc. Axios also allows you to send these requests using the request() method, which allows you to specify the request method and the endpoint as arguments.
Let's discuss GET, POST, and DELETE requests, and then we will look at their implementation.
GET Request
A GET request is an HTTP request used to retrieve information from a server. It is the most common type of request and is used to retrieve data from a web page or API.
In Axios, GET requests can be made using axios.get( url, config ) method. The first argument of this method is the URL of the endpoint, and the second argument is an optional config object that allows you to configure the request.
POST Request
A POST request is an HTTP request used to add data to the server. It is typically used when submitting a form or uploading a file. The same POST request multiple times can have different effects, like submitting a form multiple times.
The method axios.post( url, data, config ) is used to send an HTTP POST request to the given URL. It takes the URL of the endpoint, the data you want to send ( JSON object, a FormData object, a string, or any other type of data ), and an optional config object as the arguments.
DELETE Request
A DELETE request is a type of HTTP request used to delete a resource from a server. It is typically used to delete a record from a database or remove a file from a server.
The delete request is made using axios.delete(url, config ). It takes the URL and the optional config object as parameters.
Implementation of Axios
We will create a to-do app in React and will use Axios in React to fetch list items, add new items to the list, and remove items from the list.
Let’s first see the code, and then we will discuss the three requests.
Code
import { React, useState, useEffect, useRef } from "react";
import axios from "axios";
import "./App.css";
const json_URL = "http://localhost/todos/";
const App = () => {
const [todos, setTodos] = useState();
const newItemRef = useRef(null);
// Fetching data using GET
useEffect(() => {
axios.get(json_URL).then((res) => {
setTodos(res.data);
});
}, []);
// if data is not found
if (todos == null) return;
// Adding items using POST
const formHandler = () => {
axios.post(json_URL, {
Name: newItemRef.current.value,
}).then((response) => {
setTodos(response.data);
});
};
// removing items using DELETE
const removeItem = (id) => {
axios.delete(`${json_URL}${id}`).then(() => {
setTodos(todos.filter((todo_item) => todo_item.id !== id));
});
};
return (
<div>
<h1>To-Do List</h1>
<form onSubmit={formHandler}>
<input
type="text"
ref={newItemRef}
placeholder="Enter a new Item">
</input>
<button type="submit">Add Item</button>
</form>
<ul>
{todos.map((todo_item) => (
<li> {todo_item.Name}
<button onClick={() => removeItem(todo_item.id)}>Done</button>
</li>
))}
</ul>
</div>
);
};
export default App;
Explanation
The data is fetched from http://localhost/todos using a GET request, which is stored in a state variable todos. Following is the data present in the JSON file:
To add a new item, we have used ref to store the input, and when the user clicks the button to add an item, the function is called, which sends the data through the POST request. After adding a new item, the JSON file is updated:
A removeItem function is called when the user clicks on the done button. It takes an id parameter, which is passed to the axios delete request. The function then filters the items from the state, removing the item with the matching id and updating the component.
Output
Let’s see the output for GET, POST, and DELETE requests.
After Making a GET request
After Making a POST request
After Making a DELETE request
Error Handling in Axios
In Axios, error handling is typically done using the catch() method, which is called when a request fails. The catch() method takes a callback function as an argument, which will be called with the error object if the request fails.
Let's see the example for the same.
Example
We have already discussed the example of the GET method above. Suppose we modify the json_URL to an invalid one. The request will fail as the endpoint does not exist, and the catch() method will be called.
We need to add the .catch() method after the GET request to handle the error. The error will be caught, and we can display the error message using error.message.
There are many advantages of using Axios for making API requests in a JavaScript application:
Axios supports all major HTTP methods (GET, POST, PUT, DELETE, etc.), making it easy to work with RESTful APIs.
It can be used in both browser-based and Node.js environments, making it much easier for JavaScript developers.
It can transform the data of the request and response body automatically in JSON format.
Axios has a precise and clean syntax. It makes it easier for developers to make HTTP requests.
Axios supports the JavaScript Promise API, which allows the users to handle responses from the server using methods like async/await.
Need of Axios in React
Axios is a popular JavaScript library used in React to handle HTTP requests. It simplifies data fetching, API interaction, and error handling compared to the built-in fetch API. Axios offers better features like automatic JSON parsing, support for request/response interceptors, and easier configuration for headers, timeouts, and base URLs.
Promise-based Requests: Axios returns promises, making it compatible with async/await syntax for cleaner code.
Automatic JSON Parsing: Converts JSON responses to JavaScript objects automatically.
Request/Response Interceptors: Customize requests or handle errors globally.
Timeouts: Set request timeouts easily to avoid long waits.
Headers and Authorization: Configure headers, tokens, or authentication with minimal effort.
Base URLs: Define a base URL to avoid repetitive code for API endpoints.
Cross-Browser Support: Works seamlessly in older browsers by using polyfills.
File Upload/Download: Easily handle file uploads and downloads with multipart/form-data.
Frequently Asked Questions
What is Axios in React for?
Axios in React is used to handle HTTP requests, making it easy to fetch data from APIs, post data, and manage responses.
What is Axios used for in JS?
Axios is a JavaScript library for making HTTP requests. It simplifies API interactions with features like automatic JSON parsing, interceptors, and error handling.
What is the use of fetch and Axios in React?
Both fetch and Axios are used to make HTTP requests in React, but Axios offers more features like interceptors, timeouts, and simplified error handling.
Is Axios for frontend or backend?
Axios can be used for both frontend and backend development, enabling HTTP requests in client-side apps or server-side Node.js applications.
Conclusion
In this article, we have learned about React and Axios in React. We have covered the installation of Axios and the different methods with their implementation. At last, we have also understood the advantages of Axios.
If you are interested to learn further about React, you can check out our other blogs: