DEV Community

ABISHEK M
ABISHEK M

Posted on

Axios in React

When building a React application, we often need to communicate with a backend server or an API. For example, an e-commerce application may need to fetch products, add new products, update product information, or delete products. To perform these operations, we need to send HTTP requests. Axios is a popular JavaScript library used for this purpose.

Axios is a promise-based HTTP client that allows frontend applications to communicate with APIs and backend servers. We can use Axios with JavaScript, React, Node.js, and other JavaScript-based applications.

First, we need to install Axios in our React project:

npm install axios
Enter fullscreen mode Exit fullscreen mode

Then we import it into our component:

import axios from "axios";
Enter fullscreen mode Exit fullscreen mode

Axios supports different HTTP methods. The most commonly used methods are GET, POST, PUT, PATCH, and DELETE.

A GET request is used to retrieve data:

const response = await axios.get("/products");
console.log(response.data);
Enter fullscreen mode Exit fullscreen mode

A POST request is used to create new data:

axios.post("/products", {
  title: "Laptop",
  price: 50000
});
Enter fullscreen mode Exit fullscreen mode

A PUT or PATCH request is used to update existing data, while DELETE is used to remove data:

axios.delete("/products/1");
Enter fullscreen mode Exit fullscreen mode

Axios is commonly used with React's useEffect hook when we need to fetch data when a component loads. We can also use async/await with Axios to make asynchronous API calls easier to understand. Since API requests can fail, we normally use try...catch for error handling.

The easiest way to remember Axios is to think of it as a messenger between React and the backend.

React
  ↓
Axios
  ↓
API / Server
  ↓
Database
  ↓
API / Server
  ↓
Axios
  ↓
React
Enter fullscreen mode Exit fullscreen mode

In short, Axios makes API communication easier in React applications and is an important tool to learn when working with frontend applications and backend APIs.

Top comments (0)