How to use Axios with React

Introduction

Axios is a promise-based HTTP request library that is used both on the client-side and nodeJs Runtime environment. Axios provides support for request and response interceptors, transformers, and auto-conversion to JSON. It’s also protecting you by default against cross-site request forgery (XSRF).

##

In this tutorial, we’ll cover:

  • How to integrate and configure Axios in your React project
  • Where to make async requests in React
  • Using Async/Await and error handling
  • How to make GET requests
  • How to make POST requests

Let’s create a new project using create-react-app to get started. The process is very straightforward.

# Create a new app.
create-react-app axios-react-tutorial

# Move inside our new project.
cd axios-react-tutorial

# Install dependencies.
yarn add axios 

# Start the project.
yarn start

Next, open the project in your favorite editor

Integrating and configuring Axios in your React project

By default, our project is pretty empty. We’ll fix this by creating a new directory called utils. Inside, let’s also create a new file called API.js in which we’ll store our Axios configuration. For this tutorial, we will be using a fake JSON rest API server you can find it here here

// utils/API.js

import axios from "axios";

export default axios.create({
  baseURL: "https://jsonplaceholder.typicode.com",
  responseType: "json"
});

The code inside API.js imports Axios and exports a new configured instance of it. It’s set up to use the Fake JSON placeholder api as a base URL and also specify that we’d like JSON in return.

Finally, you can create a new file User.js, and inside paste the following component. The User component will serve as our user placeholder card.

import React, {useState, useEffect} from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import axios from "./utils/API.js"


const User = () =>  {
  const [user, setUser] = useState([]);

 const fetchData = async () => {
  const { data } = await axios.get("/users");
  setUser(data)
};
# making the call
useEffect(() => {
    fetchData();
  }, []);

#check if the call is succesfull
const isLoading = user.length === 0;

return (

     <div>

      {!isLoading ? (user.map((user) => (
            const {name, email, website} = user
       <div key={user.id}>

        <h4 className="mb-0">{name}</h4>
        <span className="text-muted">{email}</span>
<span className="text-muted">{website}</span>
      </div>
      ))): <p>Loding.....</p>}
    </div>
    );
  }
}

export default User;

The User component is a simple component that displays each user, his or her name email, and address inside a card. It accepts an isLoading boolean which if is set to true it will display a Loading... message. Otherwise, it will display the actual user details.

GET Requests

Note that the User component in the code above has its own state. That will help with keeping track of the data revived. It’s also using the state data to hydrate the User component when the component is re-rendered.

We also created the async function fetchData inside the User component, we make an asynchronous request to load the data and update our component’s state. That will trigger a new re-render.

Notice that the method is async which will allow us to await certain actions inside.

Next, open src/App.js and delete everything inside and replace it with the code below.

import React from "react";
import User from "./User"
funtion App () {

    return <User  />;

}

export default App;

Handling Errors with Async/Await

The usual way of handling errors in JavaScript when using promises, is via the .catch() method. The beauty of using async/await is that we can forget about that and use try/catch statements instead.

Here’s how the request above would be rewritten using try/catch.

 const fetchData = async () => {
    try {
      const { data } = await axios.get("/users");



      setUser(data);
    } catch (error) {
      console.log(error);
    }
  };

POST Requests

In Axios, you can create POST requests using the .post() method and passing the data as a second parameter. Here’s the method’s signature for your reference.

axios.post(url[, data[, config]])

Using the mocked endpoint above, let's make a POST request to the Fake rest API endpoint we have been using from the same User component:

const addUser = () => {
# random fake data
const newUser = {
    "id": 20,
    "name": "stood jakall",
    "username": "Hollame",
    "email": "hellame@april.biz",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    }}
try {
  const response = await axios.post('https://jsonplaceholder.typicode.com/users', newUser);
  console.log('👉 Returned data:', response);
} catch (e) {
  console.log(`😱 Axios request failed: ${e}`);
}

}

Conclusion

Handling requests in React with Axios is very easy to understand. There’s room for improvement, like adding more abstractions and structure also exploring other CRUD operations, you can read more about it Here