Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Know if there are pending request in axios

I'm new in ReactJS and for my ajax call I tried to use Axios library. It is awesome, but now I would like know if there is a way for know if there are pending requests in axios interceptor because, I would like, show loading overlay every ajax call (if it is not yet visibile) and remove overlay when ALL promise are resolved. For now I developed start with interceptor:

axios.interceptors.request.use(function (config) {
    //here logi of show loading
    return config;
}, function (error) {
    return Promise.reject(error);
});

And I would like add something like this:

axios.interceptors.respose.use(function (config) {
    //logic remove loading if it is last response
    return config;
}, function (error) {
    return Promise.reject(error);
});

So how, (if it is possibile) know if it's last response? Before using ReactJs, I used Angular 1.x and in $http service there was

$http.pendingRequests

There is in axios something like $http service?

like image 681
LorenzoBerti Avatar asked Jun 21 '17 08:06

LorenzoBerti


1 Answers

This was my solution :)

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);
});
like image 178
Jose Boretto Blengino Avatar answered Nov 09 '22 06:11

Jose Boretto Blengino