Access Vuex before Vue route is resolved
Going around Vanojx1's answer, I solved my question next way.
store.js
:
const store = new Vuex.Store({
state: {
authStatus: axios.get(...).then(response => {
store.commit('setAuthStatus', true)
}),
userAuth: false
},
mutations: {
setAuthStatus(state, authStatus) {
state.userAuth = authStatus
}
}
})
router.js
:
router.beforeEach((to, from, next) => {
if (to.matched.some(route => route.meta.requiresAuth)) {
store.state.authStatus.then(() => {
//we're getting 200 status code response here, so user is authorized
//be sure that API you're consuming return correct status code when user is authorized
next()
}).catch(() => {
//we're getting anything but not 200 status code response here, so user is not authorized
next({name: 'home'})
})
} else {
next()
}
})
In the navigation guard you need something async so save your axios promise in the store as authStatus. When it resolves commit and set the loggedIn status. In the navigation guard wait for the promise to be resolved and then call the next function to enter the next router.
Store.js
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
/* EXAMPLE
authStatus: new Promise(resolve => {
setTimeout(() => {
const requestResult = true;
store.commit("setAuthStatus", requestResult);
resolve(requestResult);
}, 1000);
}),
*/
authStatus: axios.get(...).then((requestResult) => {
store.commit("setAuthStatus", requestResult);
}),
loggedIn: false
},
mutations: {
setAuthStatus(state, loggedIn) {
state.loggedIn = loggedIn;
}
}
});
export default store;
router.js
router.beforeEach((to, from, next) => {
if (to.matched.some(route => route.meta.requiresAuth)) {
store.state.authStatus.then(loggedIn => {
if (loggedIn) next();
else next({ name: "home" });
});
} else {
next();
}
});
Check this solution working here