27

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?

LorenzoBerti
  • 6,704
  • 8
  • 47
  • 89
  • Another way of doing this is by using a state in your UI. For example a state in your react component called isLoading set to false first. Then when the fetch is completed, you modify the state to true. In your UI, you render the loading component if isLoading is false. Have a look at this demo that implements this: http://jsbin.com/cakireweku/edit?html,js,output – Mμ. Jun 21 '17 at 09:17
  • 1
    Thankyou, yes, but in this way I have to handle loading at every ajax call, I would like handle loading in one place, like interceptor, so I don't have to worry about setState or show loading in every call. – LorenzoBerti Jun 21 '17 at 09:33

1 Answers1

46

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);
});