Search code examples
vue.jsvuejs2vue-routervuex

How to stop the vue component to not call mounted


This is my mixin

export default {
  created () {
    if (!this.$store.getters.isAuthenticated) {
      this.$router.replace('/start')
    }
  }
}

This is my component:

import Auth from '../auth'
   
export default {
  mixins: [Auth],
  computed: {
    orders () {
      return this.$store.getters.orders
    }
  },
  mounted () {
    this.$store.dispatch('getOrders')
  }
}

Store:-

async getOrders ({ commit, state }) {
  const res = await axios.get(`${API_URL}/orders`, {
    headers: {
      'authorization': state.currentUser.token
    }
  })
  commit('setOrders', res.data)
}

The problem I am facing is, although it does redirect to '/start' when I go to '/orders', but it also start fetching the orders from mounted hook, and since currentUser is null it is giving a TypeError that Cannot read property 'token' of null. Although I can guard my getOrders function with a check if currentUser is set or not, but then I have to do it in many other functions. What I would like to happen is that after created hook mounted should not get called or any other technique anyone know better?


Solution

  • Instead of checking it the user is authenticated in a mixin use global navigation guards.

    You can either use beforeEach or beforeResolve to check if the currentUser is not null.

    import store from './store'; // import your Vuex store
    
    const router = new VueRouter({
      routes: [{
        name: 'orders',
        path: '/orders',
        meta: {
          requiresAuth: true // use this in the routes that need your currentUser
        }
      }],
    });
    
    router.beforeResolve((to, from, next) => {
      if (to.matched.some(record => record.meta.requiresAuth)) {
        if (!this.$store.getters.isAuthenticated || !store.state.currentUser) {
          next({
            name: 'forbidden' // the route the guest will be redirected to
          });
        } else {
          next();
        }
      } else {
        next();
      }
    });
    
    export default router;