reactjs axios, reactjs axios example

How to use Axios with ReactJs (Basic and Advanced concept)

Hello friends, in this tutorial we are going to learn how to use Axios with reactjs effectively. We will see examples of Axios with reactjs.

INTRODUCTION

While working on web development, we all need to fetch the data, save the data, and perform any action. In that case, we need the way to call those services we may call that REST API. Reactjs Axios is promise based due to that it gives us the ability to take advantage of Javascript async and await functionality. It gives us more readable asynchronous code.

Prerequisites

  1. Node.js version 10.16.10 or later installed on your computer.
  2. Setup new Reactjs project. (How to setup Reactjs Project).
  3. Basic understanding of HTML and javascript

Why use Reactjs Axios?

Axios is promise-based. It also provides a more flexible and powerful feature set. These are the benefit of using rectjs Axios.

  1. It supports an older browser.
  2. It has built-in CSRF protection
  3. It has the ability to cancel the requests
  4. support for upload progress
  5. Request and response interception
  6.  It has optimal timeout property in the config. There we can set the number of milliseconds before the request is aborted. For example
axios({
  method: 'post',
  url: '/user/newUser',
  timeout: 5000,    // 4 seconds timeout
  data: {
    firstName: 'John',
    lastName: 'Loe'
  }
})
.then(response => {/* handle the response */})
.catch(error => console.error('timeout exceeded'))\

7. It has Automatic JSON data transformation
8. HTTP interceptors

axios.interceptors.request.use(config => {
  // log a message before any HTTP request is sent
  console.log('Request was sent');

  return config;
});

// sent a GET request
axios.get('https://api.github.com/users/abhayhk29')
  .then(response => {
    console.log(response.data);
  });

9. Simultaneous requests
10. It Has Better Error Handling

Step 1 – Adding Reactjs Axios to the Project

In this step, we will add Axios to our project. After installing the Axios, we need to import them into our project. We are going to use a demo API endpoint(JSON Placeholder). 

npm install axios

Step 2 – Creating a Folder structure

In this step, we will create a folder in that we will create respective files for the type of method(GET, Post, Put, Delete). For extracting the user detail, we will create GetUserDetail.js.

Step 3 – Get Method (GetUserDetail.js)

In this, we are fetching all data and showing it on the screen. We have user reactjs hooks for fetching the data by using axios.

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

function GetUserDetail() {

    const [userData, setUserData] = useState([]);

    useEffect(() => {
        Axios.get('https://jsonplaceholder.typicode.com/posts')
        .then(function(res){
            setUserData(res.data);
        }).catch(function(err){
            console.log(err);
        })
    }, [])

    return (
        <div>
            {userData.map((user) => (
            <li key={user.id}>{user.title}</li>
          ))}
        </div>
    )
}
export default GetUserDetail;

We will see one more example of async and await. Here we will see how we are going to handle the async and await call in the reactjs. Async and wait are more readable as compare to classic promise based calls.

import React, { useEffect, useState } from "react";
import Axios from 'axios';
import { async } from "q";

function GetUserDetail() {

    const [userData, setUserData] = useState([]);

    const getUserDetail = async () => {
        try {
            const userData = await Axios.get('https://jsonplaceholder.typicode.com/posts');
            setUserData(userData.data);
        } catch (error) {
            console.log(error);
        }
    };

    useEffect(() => {
        getUserDetail();
    }, [])

    return (
        <div>
            {userData.map((user) => (
            <li key={user.id}>{user.title}</li>
          ))}
        </div>
    )
}
export default GetUserDetail;

Step 4 — Making a POST Request

In this step, we are going to use the POST method to create a new post. First, we will create the file CreateUserPost.js. In this section, we will use the reactjs hook method.

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

function CreateUserPost() {

    const [name, setName] = useState('');
    const handleChange = event => {
        setName(event.target.value);
    };

    const handleSubmit = event => {
        event.preventDefault();
        
        const userData = {
            name : name
        };

        Axios.post(`https://jsonplaceholder.typicode.com/posts`, {userData})
        .then(res => {
            console.log(res);
            alert(res.data.userData.name);
        }).catch(err => {
            console.log(err);
        })
    };

    return (
        <div>
            <form onSubmit={handleSubmit}>
            <label>
                Person Name:
                <input type="text" name="name" onChange={handleChange} />
            </label>
            <button type="submit">Add</button>
            </form>
        </div>
    )
}
export default CreateUserPost;

We will see the same example with the async and await method.

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

function CreateUserPost() {

    const [name, setName] = useState('');
    const handleChange = event => {
        setName(event.target.value);
    };

    const handleSubmit  = async (event) =>  {
        event.preventDefault();
        
        const userData = {
            name : name
        };

        try {
            const userDataRes = await Axios.post(`https://jsonplaceholder.typicode.com/posts`, {userData});
            if(userDataRes.status === 201){
                alert(userDataRes.data.userData.name);
            }else{
                alert('Please check your data carefully');
            }
        } catch (error) {
            console.log(error);
        }
    };

    return (
        <div>
            <form onSubmit={handleSubmit}>
            <label>
                Person Name:
                <input type="text" name="name" onChange={handleChange} />
            </label>
            <button type="submit">Add</button>
            </form>
        </div>
    )
}
export default CreateUserPost;

Step 5 — Making a DELETE Request

In this example, we see an example of the delete method. First, we will create a file DeleteUser.js. In that, we will create a form in which the user will provide an ID. By using that user will delete the user data. However, this is not a valid scenario in the real world. We have just taken an example to understand the Axios delete method.

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

function DeleteUser() {

    const [id, setId] = useState('');

    const handleChange = event => {
        setId(event.target.value);
    };

    const handleSubmit = event => {
        event.preventDefault();
        axios.delete(`https://jsonplaceholder.typicode.com/users/${id}`)
        .then(res => {
            console.log(res);
            console.log(res.data);
        }).catch(err => {
            console.log(err);
        })
    };

    return (
        <div>
            <form onSubmit={handleSubmit}>
            <label>
                Person ID:
                <input type="text" name="id" onChange={handleChange} />
            </label>
            <button type="submit">Delete</button>
            </form>
      </div>
    )
}

export default DeleteUser;

We will see same example with async and await functionality.

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

function DeleteUserAsync() {
    const [id, setId] = useState('');

    const handleChange = event => {
        setId(event.target.value);
    };

    const handleSubmit =  async (event) => {
        event.preventDefault();

        try {
            const userData = await axios.delete(`https://jsonplaceholder.typicode.com/users/${id}`);
            console.log(userData);
            if(userData.status === 200){
                alert('User deleted sucessfully');
            }else{
                alert('Please check your data carefully');
            }
        } catch (error) {
            
        }
    };

    return (
        <div>
            <form onSubmit={handleSubmit}>
            <label>
                Person ID:
                <input type="text" name="id" onChange={handleChange} />
            </label>
            <button type="submit">Delete</button>
            </form>
      </div>
    )
}

export default DeleteUserAsync;

Conclusion

In this article, we have seen an example of Axios with reactjs.
First, we have implemented the example with a simple method (Promise Based). After that, we have implemented the same code with javascript async and await functionalities. I hope we all have learned something from this article. Please provide your valuable feedback so that I can improve the quality of the tutorial. You can also share any new tutorial you want me to share. You can mail me at spycoding1@gmail.com.