user3072362
user3072362

Reputation: 35

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?

Upvotes: 0

Views: 3754

Answers (2)

Ricky Ruiz
Ricky Ruiz

Reputation: 26751

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;

Upvotes: 1

Gavin Gong
Gavin Gong

Reputation: 181

you can use route function beforeRouteEnter, if app has't authed, you can redirect to other page before enter the page need auth

Upvotes: 0

Related Questions