Quantcast
Channel: Vuex store is undefined in vue-router - Stack Overflow
Viewing all articles
Browse latest Browse all 2

Vuex store is undefined in vue-router

$
0
0

I have a router and a global beforeEach hook to validate auth.

import store from "@/store/store";const router = new Router({    // routes...});router.beforeEach((to, from, next) => {    if (to.matched.some(record => record.meta.requiresAuth)) {        if (!store.getters.getAccessToken) { //undefined store            next("/access/login");        }    }    else {        next();    }});export default router;

And in my store/store.js file, I have an action that makes a request to validate user/password, and then tries to redirect to / route (protected route).

import router from "@/router";//state, getters...actions: {    login({commit}, authData) {        // axios instance prototyped into vue $http object        this._vm.$http.post("/auth/login", authData)            .then(response => {                commit("saveToken", response.data.token);            })            .catch((error) => {                commit("loginError", error.response.data);            });    }},mutations: {    saveToken(state, token) {        state.accessToken = token;        router.push({            path: "/"        });    },    loginError(state, data) {        return data.message;    }}

The problem I have is that the store in router.js is undefined. I have checked all imports, routes, and names several times, and they're fine.

Could it be a problem with the circular reference due to me importing router in the store and store in the router?

If that's the problem, how can I access the store from the router or the router from the store?

EDIT

I've tried to remove the router import from the store, and it works fine with the exception of:

router.push({    path: "/"});

because router is not imported.

EDIT: ADDED @tony19 SOLUTION

I've applied the solution that @tony19 provides and it works fine, but when I access the / route, router.app.$store is undefined.

The fixed code:

router.beforeEach((to, from, next) => {    console.log(`Routing from ${from.path} to ${to.path}`);    if (to.matched.some(record => record.meta.requiresAuth)) {        if (!router.app.$store.getters["authentication/getAccessToken"]) {            next("/access/login");        }        else {            next();        }    }    else {        next();    }});

An image with the debugging session:

enter image description here


Viewing all articles
Browse latest Browse all 2

Trending Articles