Know if there are pending request in axios

16,019

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);
});
Share:
16,019

Related videos on Youtube

LorenzoBerti
Author by

LorenzoBerti

Updated on September 15, 2022

Comments

  • LorenzoBerti
    LorenzoBerti over 1 year

    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?

    • Mμ.
      Mμ. almost 7 years
      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: jsbin.com/cakireweku/edit?html,js,output
    • LorenzoBerti
      LorenzoBerti almost 7 years
      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.
  • Ukor
    Ukor about 6 years
    This was helpful. Ajax request should go after this.
  • hugo der hungrige
    hugo der hungrige almost 4 years
    Shouldn't numberOfAjaxCAllPending-- also be called on error?