axios check if call is already running 1

axios check if call is already running

var numberOfAjaxCAllPending = 0;

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    numberOfAjaxCAllPending++;
    // show loader
    return config;
}, function (error) {
    return Promise.reject(error);
});

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    numberOfAjaxCAllPending--;
    console.log("------------  Ajax pending", numberOfAjaxCAllPending);

    if (numberOfAjaxCAllPending == 0) {
        //hide loader
    }
    return response;
}, function (error) {
    numberOfAjaxCAllPending--;
    if (numberOfAjaxCAllPending == 0) {
        //hide loader
    }
    return Promise.reject(error);
});

Here is what the above code is Doing:
1. We are creating a global variable numberOfAjaxCAllPending and setting it to 0.
2. We are adding a request interceptor to axios. This interceptor will be called before every request.
3. In the request interceptor, we are incrementing the numberOfAjaxCAllPending variable.
4. If the numberOfAjaxCAllPending is greater than 0, we are showing the loader.
5. We are adding a response interceptor to axios. This interceptor will be called after every response.
6. In the response interceptor, we are decrementing the numberOfAjaxCAllPending variable.
7. If the numberOfAjaxCAllPending is 0, we are hiding the loader.

Similar Posts