Dev.to WebDev 🛠 Dev 👁 0 📖 4 min read

Axios in React

What is Axios? Axios is a JavaScript library used to make HTTP requests. In a React application, it is commonly used to communicate with APIs and backend servers. Through Axios, a React application can send requests to

What is Axios?

Axios is a JavaScript library used to make HTTP requests. In a React application, it is commonly used to communicate with APIs and backend servers. Through Axios, a React application can send requests to a server and receive data from it.

For example, a React application may need to get a list of movies from an API, send a new user to a backend, update existing data, or delete a record. Axios provides methods such as get(), post(), put(), patch(), and delete() for these operations.

The basic flow can be understood as:

React Application
       ↓
     Axios
       ↓
   HTTP Request
       ↓
      API
       ↓
   HTTP Response
       ↓
     Axios
       ↓
React Application

Axios itself is not a database and does not permanently store the data. Its main responsibility is communication between the application and the server.

Installing Axios

Axios can be installed in a React project using:

npm install axios

After installing it, import Axios into the component or JavaScript file where it is required:

import axios from "axios";

Now Axios methods can be used to communicate with APIs.

Axios GET Request

The GET method is used when we want to retrieve data from a server.

const response = await axios.get("https://example.com/users");

console.log(response.data);

Axios returns a response object that contains information such as the response data, status, and headers. The actual data returned by the server is normally accessed using response.data.

For example, if the API returns an array of users:

[
  {
    id: 1,
    name: "John"
  },
  {
    id: 2,
    name: "David"
  }
]

then response.data contains this array.

Using GET in React

When data needs to be fetched when a component loads, Axios is commonly used inside useEffect().

import { useEffect, useState } from "react";
import axios from "axios";

function App() {

  const [users, setUsers] = useState([]);

  useEffect(() => {

    const getUsers = async () => {
      const response = await axios.get(
        "https://example.com/users"
      );

      setUsers(response.data);
    };

    getUsers();

  }, []);

  return (
    <div>
      {users.map((user) => (
        <div key={user.id}>
          <h2>{user.name}</h2>
        </div>
      ))}
    </div>
  );
}

Initially, users is an empty array. The component renders, and then the effect runs. Axios sends the GET request. After the server responds, setUsers() updates the state. React then re-renders the component, and map() creates the UI for each user.

The flow is:

Component renders
       ↓
useEffect runs
       ↓
Axios sends GET request
       ↓
Server sends response
       ↓
response.data
       ↓
setUsers()
       ↓
React re-renders
       ↓
map() creates UI

Mapping API Data in React

APIs frequently return an array of objects. React can use the JavaScript map() method to convert every object into JSX.

Suppose the API returns:

[
  {
    imdbID: "tt001",
    Title: "Avatar"
  },
  {
    imdbID: "tt002",
    Title: "Titanic"
  }
]

It can be displayed like this:

<ul>
  {movie.map((x) => (
    <li key={x.imdbID}>
      <h1>{x.Title}</h1>
    </li>
  ))}
</ul>

Here, map() goes through the array one object at a time. During each iteration, x represents the current movie object.

For the first object:

x = {
  imdbID: "tt001",
  Title: "Avatar"
}

Therefore:

x.imdbID

gives "tt001" and:

x.Title

gives "Avatar".

The same process happens for every object in the array.

The key helps React identify each item in the list. A unique identifier from the API, such as imdbID, is generally preferable to using the array index.

Axios POST Request

The POST method is generally used to send data to a server, often to create a new resource.

The first argument is the URL, and the second argument is the data that should be sent to the server.

The basic structure is:

axios.post(url, data);

For example, when a user submits a form in React, the form data can be sent using Axios:

const addUser = async () => {

  const user = {
    name: "John",
    age: 22
  };

  const response = await axios.post(
    "https://example.com/users",
    user
  );

  console.log(response.data);
};

Dynamic GET Requests

The URL of a GET request can also be created based on user input.

For example:

const username = "john";

const response = await axios.get(
  `https://example.com/users/${username}`
);

The resulting URL is:

https://example.com/users/john

Template literals are useful for creating dynamic URLs.

Axios also supports query parameters through the params option:

const response = await axios.get(
  "https://example.com/movies",
  {
    params: {
      name: "Avatar"
    }
  }
);

This produces a request containing a query parameter such as:

https://example.com/movies?name=Avatar

Using params is often cleaner than manually constructing a long query string.

Other Axios Methods

Axios supports the common HTTP methods used for CRUD operations.

CREATE → POST
READ   → GET
UPDATE → PUT / PATCH
DELETE → DELETE

For example:

axios.get("/users");
axios.post("/users", user);
axios.put("/users/10", user);
axios.patch("/users/10", { name: "David" });
axios.delete("/users/10");

PUT is generally used to replace or update a resource, while PATCH is generally used for a partial update.

Error Handling

HTTP requests can fail for many reasons. The server may be unavailable, the URL may be incorrect, the user may not be authorized, or the network connection may fail.

Axios requests can be handled using try...catch:

try {

  const response = await axios.get(url);

  console.log(response.data);

} catch (error) {

  console.log(error);

}

Headers

Some APIs require additional information in the request. This information can be sent using HTTP headers.

For example:

axios.get(url, {
  headers: {
    Authorization: `Bearer ${token}`
  }
});

Headers are often used for authentication and other request metadata.

For a POST request, Axios can receive the request data and configuration separately:

axios.post(
  url,
  userData,
  {
    headers: {
      Authorization: `Bearer ${token}`
    }
  }
);

The three arguments are:

URL
 ↓
Data
 ↓
Configuration

Axios Instances

In larger applications, the same API base URL may be used repeatedly. Instead of writing the complete URL every time, an Axios instance can be created.

const api = axios.create({
  baseURL: "https://example.com/api"
});

Now requests can be written as:

api.get("/users");
api.post("/users", user);

This makes API-related code easier to organize and maintain.

Read more about axios

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.