farid
farid

Reputation: 1494

problem with using axios interceptors in react

I want to get fetching status when make and send requests using axios. I thought that I can achieve this by using axios interceptors. I try this code:

./axiosInstance.js

let fetching = false;

const axiosInstance = axios.create();

axiosInstance.interceptors.request.use(config => { 
    fetching = true;
    console.log("first log: ", fetching);
    return config;
}, () => { fetching = false });

axiosInstance.interceptors.response.use(() => { 
    console.log("second log: ", fetching);
    fetching = false;
    console.log("third log: ", fetching);
});

export { fetching, axiosInstance };

And this is how I make and send requests using my own instance of axios that I created:

./component.js

import { fetching, axiosInstance } from "./axiosInstance";

const Component = () => {

    const sendRequest = () => {
        axiosInstance.get("someUrl:somePort/");
    };

    return (
        <>
            <button type="button" onClick={ sendRequest }>click</button>
            <p>{ fetching ? "true": "false" }</p>
        </>
    );
}

export default Component;

But the problem is, this is not work. I get logs in ./axiosInstance.js as I expected:

first log: true
second log: true
third log: false

But I have a <p> tag in ./component.js that I use it to show value of the fetching variable that I get it from ./axiosInstance.js. and its value never change to true and it's always false.

<p>{ fetching ? "true": "false" }</p>

Upvotes: 3

Views: 1795

Answers (1)

grudev
grudev

Reputation: 635

import {useState} from 'react';

const [fetching, setFetching] = useState(false);

const axiosInstance = axios.create();

axiosInstance.interceptors.request.use(config => { 
    setFetching(true);
    console.log("first log: ", fetching);
    return config;
}, () => { fetching = false });

axiosInstance.interceptors.response.use(() => { 
    console.log("second log: ", fetching);
    setFetching(false);
    console.log("third log: ", fetching);
});

export { fetching, axiosInstance };

You can use fetching as a state. It will be working.

Upvotes: 2

Related Questions