[Vuejs]-Too many requests when controlling spinner show/hide from axois interceptors

0👍

In the main.js file

Vue.prototype.$axios = axios.create(
  {
    headers:
      {
        'Content-Type': 'application/json',
      },
    baseURL: process.env.API_URL
  }
);

Vue.prototype.$axios.interceptors.request.use(
  config =>
  {
    eventBus.$emit('show_spin');
    let token = getTokenID();
    if(token && token.length) config.headers['Authorization'] = token;
    return config;
  },
  error =>
  {
    eventBus.$emit('hide_spin');
    if (error.status === 401) VueRouter.push('/login');
    else throw error;
  }
);
Vue.prototype.$axios.interceptors.response.use(
  response =>
  {
    eventBus.$emit('hide_spin');
    return response;
  },
  error =>
  {
    eventBus.$emit('hide_spin');
    return new Promise(function(resolve,reject)
    {
      if (error.config && error.response && error.response.status === 401 && !error.config.__isRetry)
      {
        myVue.refreshToken(function()
        {
          error.config.__isRetry = true;
          error.config.headers['Authorization'] = getTokenID();
          myVue.$axios(error.config).then(resolve,reject);
        },function(flag) // true = invalid session, false = something else
        {
          if(process.env.NODE_ENV === 'development') console.log('Could not refresh token');
          if(getUserID()) myVue.showFailed('Could not refresh the Authorization Token');
          reject(flag);
        });
      }
      else throw error;
    });
  }
);

let myVue = new Vue(
{
  el: '#app',
  data: function()
  {
    return {
      spin_visible: 0, // dynamically show/hide spinner
    };
  },
  created: function()
  {
    eventBus.$on('show_spin', this.showSpin);
    eventBus.$on('hide_spin', this.hideSpin);
  },
  methods:
  {
    showSpin: function()
    {
      this.spin_visible++;
    },
    hideSpin: function()
    {
      if(this.spin_visible>0) this.spin_visible--;
    }, 
    ....

and then in App.vue

<template>
  <router-view/>
  <div class="spinner" v-show="$root.spin_visible"> 
  <!-- define your spinner here -->
  </div>
</template>

Leave a comment