Search code examples
javascriptvue.jsvue-componentvuexvue-router

Vue: How to use Per-Route Guard with Vuex getter?


Similar to the way that we handle with isAuthenticate function to check if user has properly authenticated, I'm trying to inspect in my store.

const state = {
    cliente: []
};

const getters = {
    //Verificar Regra
    CHECK_CLIENTE_STATE: (state) => {
        return state.cliente
    }
}

const actions = {
    FETCH_DADOS({ commit }, obj) {
        return fetch(`http://localhost:3030/pessoas/informacao/${obj['data']}`)
            .then(response => response.json())
            .then(data => commit('SetCliente', data))
            .catch(error => console.log(`Fetch: ${error}`))
    }
}

const mutations = {
    SetCliente(state, cliente) {
        state.cliente = cliente
    }
}

login page,

  methods:{
    fetch(){
      this.$store.dispatch("FETCH_DADOS",{'data':'12345'})
      this.$router.push('/') 
    }
  }

At the first fetch click, I inspect Vuex, apparently it is working.

enter image description here

Routes:

const routes = [{
        path: '/',
        beforeEnter: (to, from, next) => {
            if (store.getters.CHECK_CLIENTE_STATE == '') {
                next('/login')
            }
            next();
        },
        component: () =>
            import ('../views/Home')
    },
    {
        path: '/login',
        component: () =>
            import ('../views/Login')
    }
]

Well, in console.log at the first fetch click, I receive this error, but in vuex as shown above, the store is filled.

Uncaught (in promise) Error: Redirected when going from "/login" to "/" via a navigation guard.

Why just in the second click is it redirected to home, not in the first?

Updating

Trying a new approach in router.js

path: '/',
beforeEnter: (to, from, next) => {
    console.log(!store.getters.CHECK_CLIENTE_STATE.length)
    if (!store.getters.CHECK_CLIENTE_STATE.length) {
        next('/login')
    }
    next();
},
component: () =>
    import ('../views/Home')

But again, the first fetch is TRUE and the second FALSE, in the second I'm redirected to /home


Solution

  • The router is being directed before the data is loaded. Wait for it:

    methods:{
      async fetch(){
        await this.$store.dispatch("FETCH_DADOS",{'data':'12345'})
        this.$router.push('/') 
      }
    }