Logo


How to use axios interceptors in React JS


In this article, we are going to learn how to intercept every request or response that is being sent by Axios Interceptors in a React application.
Axios interceptors are the default configurations that are added automatically to every request or response that a user receives. It is useful to check response status code for every response that is being received.


Example

In this example, we will make a React application that automatically checks and logs the status code that is sent by the server while sending a POST request from our React application. We have to set all the configuration in the most global file, i.e. index.js, to intercept every request/response.Learn with examples.

App.js file is displayed below:

1
2import "./styles.css";
3import React from 'react';
4import axios from 'axios'
5export default class App extends React.Component {
6 constructor(props)
7 {
8   super(props)
9   this.state={
10     data:"",
11     val:"",
12     fetchData:false,
13   }
14 };
15
16 getstatus=()=>{
17  this.setState({
18    fetchData:true
19  },()=>this.getValue())
20 }
21 
22 getValue=()=>{
23  if(this.state.fetchData)
24  {
25    console.log("hi")
26    const payload={
27    body:JSON.stringify({title:this.state.val})
28    }
29    axios.post('https://jsonplaceholder.typicode.com/posts', payload)
30    .then((res) => this.setState({data:res.data.id}));
31
32 }
33}
34  render() {
35    return <>  {this.state.data && <h1>Your data is saved with Id: {this.state.data}</h1>} <input
36    placeholder="Title of Post"
37    value={this.state.val}
38    onChange={(e) => this.setState({val:e.target.value})}
39   
40 />
41  <button onClick={(e) => this.getstatus()} >Save Data</button>
42 </>;
43  }
44}

index.js file is displayed below

1import { StrictMode } from "react";
2import ReactDOM from "react-dom";
3import axios from 'axios'
4
5import App from "./App";
6axios.interceptors.response.use(
7  (res) => {
8     // Add configurations here
9     if (res.status === 201) {
10        console.log('Posted Successfully');
11     }
12     return res;
13  },
14  (err) => {
15     return Promise.reject(err);
16  }
17);
18
19const rootElement = document.getElementById("root");
20ReactDOM.render(
21  <StrictMode>
22    <App />
23  </StrictMode>,
24  rootElement
25);

Here is the link of live example which we done so far:
Click here

About

Moiz is a software engineer from Arid University with a passion for writing tech tutorials and doing coding. I am continously produce JavaScript and other web development technology tutorials in concepts through easy-to-understand explanations written in plain English.I have expertise in next js ,react js ,javascript,html,bootstrap and node js.

Follow him on Twitter

Hassan is a software engineer from kohat university of science and technology with a passion for writing tech tutorials and doing javascript practices on daily basis.I have expertise in next js ,react js ,javascript,html,bootstrap and node js. Problem Solving and making concpets is my strong point.

Follow him on Twitter

Tags

Click to see all tutorials tagged with:

© Copyright 2023 Pak Annonymous | Back To Homepage | Privacy Policy
Share