How To Use  Axios Library In React.js

How To Use Axios Library In React.js

Table Of Contents

  1. Introduction

  2. Prerequisites

  3. What is Axios

  4. Way Use Axios In React

  5. Installation

  6. How To Get Different Requests with Axios GET, POST, PUT and DELETE

  7. How To Handle Errors In Axios

  8. Conclusion

INTRODUCTION:

In this article, we are going to know what an Axios is and why it is commonly used by developers.

PREREQUISITES:

. Node.js installed

. A new react app set up

. An IDE or text editor of your choice

WHAT IS AXIOS:

Axios is a javascript library that is used to perform HTTP requests from the web browser and node.js server. It is also used to make an API request, that returns data from an API, which enables us to perform certain functions with the data in our React Application.

WAY TO USE AXIOS IN REACT:

Here are reasons why the Axios library is the most popular used to perform requests from the web browser;

  1. It has a function name that matches the request method, you are trying to perform

  2. Axios is a promise-based HTTP client for Javascript, this allows for more readable code and easy error handling.

  3. Provide API data with less code. Unlike the fetch method, Axios only needs one .then() callback to access requested JSON Data.

  4. Axios supports Interceptors which are default configuration that is added automatically to every request or response that a user receives before they are handled by the application. This helps in handling errors in a more centralized way and is useful in adding authentication headers.

Overall, Axios in React improves HTTP request, increases code readability, supports interceptors and make JSON data handling easy. This makes it an important library for building modern web applications

INSTALLATION:

first let's create our react-app by running the following command in our terminal

nxp create-react-app react-axios-practice

We now navigate to the folder.

cd react-axios-practice

Our project should look like this

To install Axios in React we will run the following command.

npm i --save axios

After installation it is important you check if the library is inside your dependencies, to check this we have to navigate to package-lock-json

HOW TO GET DIFFERENT REQUESTS FROM AN API USING AXIOS :

In this section, we are going to learn how to make multiple requests using the Axios library. We will perform this request using https://jsonplaceholder.typicode.com/posts. So we will be creating 4 different components inside the src file and that will be Post.js for a GET request, AddPost.js for a POST request, UpdatePost.js for PUT request, and DeletePost.js for DELETE request.

  1. HOW TO MAKE A GET REQUEST IN AXIOS :

To fetch data or retrieve data is what we use the GET request to do. The following line of code will be embedded inside Post.js file.

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

const url = "https://jsonplaceholder.typicode.com/posts";

function Post() {
  const [post, setpost] = useState([]);

  useEffect(() => {
    axios
      .get(`${url}/1`)
      .then((response) => {
        setPost(response.data);
      })
      .catch((error) => {
        console.error(error);
      });
  }, []);

  return (
    <div>
      <main className="img">
        <h5>{Post.title}</h5>
        <p>{post.body}</p>
      </main>
    </div>
  );
}

export default Post;

First, we import useState, useEffect hook and also the Axios library to help us perform our HTTP request. We will perform the HTTP request inside the useEffect arrow function, we use the GET method to make a request to our endpoint and use the then callback method to get back all our response data and update our useState.

We will receive an object as our response, The data is placed inside our state state called post with properties of id, title, body, userId. For just example sake, I decided to just collect only one product

Note, we can also perform other response

Next, we added our post.js to our App.js

  1. HOW TO MAKE A POST REQUEST IN AXIOS :

we will make a post request with the Axios library. Making a post request means adding new data to the already known data, a real-life example can be submitting a web form or when uploading a file to the web. But in our example, we will continue using our https://jsonplaceholder.typicode.com/posts API. We will be writing our code inside the AddPost component

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

const url = "https://jsonplaceholder.typicode.com/posts/";

function AddPost() {
  const [addPost, setAddPost] = useState("");

  const handlePost = () => {
    const newPost = {
      userId: 1,
      title: "This is a new post",
      body: "Lorem ipsum dolor sit amet consectetur adipisicing elit. Itaque, molestiae.",
    };

    axios.post(url, newPost).then((res) => {
      setAddPost(res.data);
    });
  };

  return (
    <div className="img">
      <h5>{addPost.title}</h5>
      <p>{addPost.body}</p>
      <button type="button" onClick={handlePost}>
        post
      </button>
    </div>
  );
}

export default AddPost;

Just like the GET request we first import our useState and axios library, Then save our data in a const url variable. To make a post request we use the .post method, so in our example we made a post request to the jsonplaceholder post API with a newPost data object containing userId, title, body. Once again we use the .then method to get the response data. Lastly, we call our handlePost function inside our react component JSX code.

Note: In a real-life situation we would likely want to use the user input to generate the data object sent in the post request, instead of hard coding it as we did above.

  1. HOW TO MAKE A PUT REQUEST IN AXIOS :

essentially what we do whenever we make a PUT request is to update a resource. In our example, we will be updating our first post.

import React from "react";
import axios from "axios";

const url = "https://jsonplaceholder.typicode.com/posts/";

function UpdateProduct() {
  const [post, setPost] = React.useState("");

  React.useEffect(() => {
    axios.get(`${url}/1`).then((res) => {
      setPost(res.data);
    });
  }, []);

  function updatePost() {
    axios
      .put(`${url}/1`, {
        title: "This Post Is Updated",
        body: "this post has been updated before using the put method in axios library",
      })
      .then((res) => {
        setPost(res.data);
      });
  }

  return (
    <div className="img">
      <h5>{post.title}</h5>
      <p>{post.body}</p>
      <button type="button" onClick={updatePost}>
        Update Post
      </button>
    </div>
  );
}

export default UpdateProduct;

In the code above we use the PUT method to update the resource. Same as the POST request we added properties that would update the resource. With an updatePost onClick function that would be used to trigger the updated resource in our project.

  1. HOW TO MAKE A DELETE REQUEST IN AXIOS :

To make a DELETE request, means you are about to delete a resource. In our code below we will be implementing the delete request on the first post of our API

import React from "react";
import axios from "axios";

const url = "https://jsonplaceholder.typicode.com/posts/";

function DeleteProduct() {
  const [post, setPost] = React.useState(null);

  React.useEffect(() => {
    axios.get(`${url}/1`).then((res) => {
      setPost(res.data);
    });
  }, []);

  function deletePost() {
    axios.delete(`${url}/1`).then(() => {
      alert("Post deleted");
      setPost("");
    });
  }

  if (!post) return "No Post";

  return (
    <div className="post">
      <h5>{post.title}</h5>
      <p>{post.body}</p>

      <button type="button" onClick={deletePost}>
        Delete Post
      </button>
    </div>
  );
}

export default DeleteProduct;

In our code above we called the DELETE request on our jsonplaceholder API and used the .then() callback function to make sure the data is resolved successfully.

In our code, we also made an alert that tells the user that the post has been deleted, And the post request is cleared out of the state by setting it to an empty string.

  1. HOW TO HANDLE ERRORS IN AXIOS.

Axios is also capable of handling errors when making an HTTP request from the web.

These errors can occur due to many reasons for example, when we enter a wrong endpoint, a network issue and passing the wrong data.

In our example, we will be doing all of our error handling inside the catch block

let's show some examples below;

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

const url = "https://jsonplaceholder.typicode.com/posts/";
function HandlingErrors() {
  useEffect(() => {
    axios
      .get(`${url}ggg`)
      .then((res) => {
        console.log(res.data);
      })
      .catch((error) => {
        if (error.response) {
          // // The client was given an error response (5xx, 4xx)
          console.log("Data:" ,error.response.data);
          console.log("Status:", error.response.status);
        } else if (error.request) {
          // This request was made but no response was found
          console.log(error.request);
        } else {
          // This can be any other reason
          console.log(Error, error.message);
        }
      });
  }, []);

  return <div></div>;
}

export default HandlingErrors;

Each statement within the catch block explains multiple issues our request might encounter. Don't worry we will explain each of them one by one

error. response ;

This is a type of error we are most familiar with, and is easier to handle. This error displays a 404/page not found error message based on what the API provides. This error is easily handled in the response.

error. request ;

This error is often associated with bad/poor network when the backend does not return a response on time. An unauthorized cross-domain request, or you might be making an authorized cross-domain but your request throws an error.

other error ;

If your error object is not response or request field on it, that means it's not an Axios error and there is something wrong with your app.

CONCLUSION

In this article, we've been able to cover Axios to some extent. Explaining what Axios is and how to use it in our react app, Especially how to run the GET,POST,PUT and DELETE request.