How To Use Interceptor In ReactJS

In this article, we will learn how to use interceptor in reactjs.

Interceptors are used to automatically check the logs and the API status code which is sent by the server.

–First of all, we have create react application.

-Then add the Axios package to your project

npm i axios

-Now add your interceptor code to the index.js file:

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import axios from "axios";

axios.interceptors.response.use(
  (response) => {
    if (response.data.success === false && response.data.message === "Unauthenticated Invalid Token") {
     alert("Invalid Token")
    }
    else {
      return response;
    }
  }
);

API call:

import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import Navbar from "../../../layout/Navbar";
import BootstrapTable from 'react-bootstrap-table-next';
import { listGender } from '../../../../api-wrapper/master-wrapper/ApiGender';

const GenderList = () => {
    const [genderList, setGenderList] = useState([]);
    // table columns
    const columns = [
        {
            dataField: 'gender',
            text: 'Gender'
        }, {
            dataField: 'status',
            text: 'Status',
            formatter: function (cell) {

                if (cell === 'A') {
                    return (
                        <div className="badge active">{cell}</div>
                    )
                }
                if (cell === 'I') {
                    return (
                        <div className="badge inactive">{cell}</div>
                    )
                }
            }
        }];


    // *** Gender List Data Get *** //
    useEffect(() => {
        listGender()
            .then((res) => {
                setGenderList(res.data.data)
            }).catch((err) => {
                console.log(err)

            });
    }, []);


    return (
        <>
            <div className="container master-wrapper">
                <div className="table-wrapper">
                    <BootstrapTable keyField='id' data={genderList && genderList.length ? genderList : ''} columns={columns} />
                </div>
            </div>


        </>
    )
}

export default GenderList;

-when the API response is false and the message is an unauthenticated invalid token then the interceptor returns the alert message otherwise it returns the API response.

OUTPUT:

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories