26

I'm currently building a vue app and Im using axios. I have a loading icon which i show before making each call and hide after.

Im just wondering if there is a way to do this globally so I dont have to write the show/hide loading icon on every call?

This is the code I have right now:

context.dispatch('loading', true, {root: true});
axios.post(url,data).then((response) => {
        // some code
        context.dispatch('loading', false, {root: true});
    }).catch(function (error) {
        // some code
        context.dispatch('loading', false, {root: true});color: 'error'});
    });

I have seen on the axios docs there are "interceptors" but II dont know if they are at a global level or on each call.

I also saw this post for a jquery solution, not sure how to implement it on vue though:

$('#loading-image').bind('ajaxStart', function(){
    $(this).show();
}).bind('ajaxStop', function(){
    $(this).hide();
});
3
  • 4
    Interceptors can be used globally or only for some requests if you wish (just create an instance with them, and only use this instance when you want a request to change the loading status). But... I'm not sure about the concept of having each request turn the loading status on and off. In some cases, you might want to run multiple requests at the same time. If one of them is faster than the other, it will set the loading status to false, while the other is still pending. Might not be a problem in your case, but it's important to consider.
    – blex
    Jun 8, 2018 at 22:13
  • Is there a more generic way of detecting if there are any requests pending?
    – Brad
    Jun 8, 2018 at 22:34
  • 2
    There may be other ways, but one I can think of would be to have a pending requests counter in your store (or somewhere else, where you initialize axios for example). Initialize it to zero, and every time you start a request, add 1 to it and set the loading status to true. After a request is complete (either resolved or rejected), substract 1, and only if the counter equals 0, set the loading status to false.
    – blex
    Jun 8, 2018 at 22:38

3 Answers 3

42

I would setup Axios interceptors in the root component's created lifecycle hook (e.g. App.vue):

created() {
  axios.interceptors.request.use((config) => {
    // trigger 'loading=true' event here
    return config;
  }, (error) => {
    // trigger 'loading=false' event here
    return Promise.reject(error);
  });

  axios.interceptors.response.use((response) => {
    // trigger 'loading=false' event here
    return response;
  }, (error) => {
    // trigger 'loading=false' event here
    return Promise.reject(error);
  });
}

Since you could have multiple concurrent Axios requests, each with different response times, you'd have to track the request count to properly manage the global loading state (increment on each request, decrement when each request resolves, and clear the loading state when count reaches 0):

data() {
  return {
    refCount: 0,
    isLoading: false
  }
},
methods: {
  setLoading(isLoading) {
    if (isLoading) {
      this.refCount++;
      this.isLoading = true;
    } else if (this.refCount > 0) {
      this.refCount--;
      this.isLoading = (this.refCount > 0);
    }
  }
}

demo

0
8

I think you are on the right path with dispatch event when ajax call start and finish.

The way that I think you can go about it is to intercept the XMLHttpRequest call using axios interceptors like so:

axios.interceptors.request.use(function(config) {
  // Do something before request is sent
  console.log('Start Ajax Call');
  return config;
}, function(error) {
  // Do something with request error
  console.log('Error');
  return Promise.reject(error);
});

axios.interceptors.response.use(function(response) {
  // Do something with response data
  console.log('Done with Ajax call');

  return response;
}, function(error) {
  // Do something with response error
  console.log('Error fetching the data');
  return Promise.reject(error);
});

function getData() {
  const url = 'https://jsonplaceholder.typicode.com/posts/1';
  axios.get(url).then((data) => console.log('REQUEST DATA'));
}

function failToGetData() {
  const url = 'https://bad_url.com';
  axios.get(url).then((data) => console.log('REQUEST DATA'));
}
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<button onclick="getData()">Get Data</button>
<button onclick="failToGetData()">Error</button>

5

For Nuxt with $axios plugin

modules: ['@nuxtjs/axios', ...]

plugins/axios.js

export default ({ app, $axios ,store }) => {
  const token = app.$cookies.get("token")
  if (token) {
    $axios.defaults.headers.common.Authorization = "Token " + token
  }
  $axios.interceptors.request.use((config) => {
    store.commit("SET_DATA", { data:true, id: "loading" });
    return config;
  }, (error) => {
    return Promise.reject(error);
  });

  $axios.interceptors.response.use((response) => {
    store.commit("SET_DATA", { data:false, id: "loading" });
    return response;
  }, (error) => {
    return Promise.reject(error);
  })
}

store/index.js


export default {
  state: () => ({
    loading: false
  }),
  mutations: {
    SET_DATA(state, { id, data }) {
      state[id] = data
    }
  },
  actions: {
    async nuxtServerInit({ dispatch, commit }, { app, req , redirect }) {
      const token = app.$cookies.get("token")
      if (token) {
        this.$axios.defaults.headers.common.Authorization = "Token " + token
      }
      let status = await dispatch("authentication/checkUser", { token })
      if(!status) redirect('/aut/login')
    }
  }
}

This example is accompanied by a token check with $axios and store

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.