The Vuex store has not been defined in the vue-router

I'm currently facing an issue with my router setup and a global beforeEach hook that validates authentication.

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;

In my store/store.js file, I have an action that verifies user credentials and then attempts to redirect to the protected / route.

import router from "@/router";

//state, getters...

actions: {
    login({commit}, authData) {
        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 challenge I am encountering is that the store in router.js seems to be undefined. Despite thorough checks of imports and naming, the issue persists.

Could this be a result of a circular reference caused by importing router in the store and vice versa?

If so, how can I resolve this to access the store from the router or vice versa?

EDIT

Attempts to remove the router import from the store yielded success except for:

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

due to the absence of the imported router.

EDIT: ADDED @tony19 SOLUTION

Following the solution provided by @tony19, things seem to work smoothly. However, upon accessing the / route, router.app.$store appears undefined.

The revised code snippet:

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 accompanying image showcasing the debugging session:

https://i.sstatic.net/DbiHJ.png

Answer №1

This issue is actually stemming from the circular reference problem. To work around this, you can refrain from importing the store in router.js and instead utilize router.app. This will give you access to the Vue instance that the router is injected into. By using router.app.$store, you can easily retrieve the store:

router.beforeEach((to, from, next) => {
  /* ... */
  if (!router.app.$store.getters.getAccessToken) {
    next("/access/login");
  }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

`Switching the selection in ng-selected`

I am having trouble toggling ng-selected options in Angular. I have tried the following approach: <select ng-model="datacut.ages" multiple> <option value="" disabled="disabled">Please Select</option> <option value="0-15" ng-clic ...

Having Trouble with the JSX React HTML5 Input Slider

I'm currently utilizing React.JS for a project, where I am creating a range input slider with two options as part of a component. This is the code snippet in question: <input id="typeinp" type="range" min="0" max="5" value="3" step="1"/> Upon ...

Passing props dynamically with TypeScript ENUMs

As I begin learning TypeScript with React, I am creating practice scenarios to enhance my understanding along the way. export enum Colors { Blue = "#0000FF", Red= "#FF0000", Green = "#00FF00", } export const ColorComponent: React.FC<props> = ...

New Vuetify component for customizing data iterators with specific key names

Can I customize the key names in the Vuetify v-data-iterator component? https://i.sstatic.net/Znv41.jpg I need to change the header names without altering the property names inside the "items" array. How can I achieve this when dealing with special chara ...

Error: A valid root path is needed for this operation to proceed

While setting up a basic node/express server, I encounter the error message shown below. An issue has occurred: TypeError: root path required I am seeking guidance on how to resolve this error. Your assistance is much appreciated. Thank you. var nod ...

Conceal the div element if the value exceeds 0

I'm looking for a way to display a div when the number of remaining days is less than 0. I got it working on jsfiddle, but for some reason, it doesn't work anywhere else. if ($('.daysrem&a ...

Events bound to JSX elements created in an array map are not being triggered by React

My current task involves working on a compact react + typescript (1.6) application designed for editing slideshows. The functionality of the app is straightforward. A sidebar on the left displays all existing slides, and upon clicking, a canvas appears on ...

Ways to guide user after logging out

My Angular front end includes the following code in app.js to handle user logout: .when('/logout', { templateUrl: 'mysite/views/logout.html', resolve: { authenticated: ['djangoAuth', function(djangoAuth){ return ...

Navigating through async functions in an Express.js router

Encountered a lint error indicating that Promises cannot be returned in places where a void is expected. Both functions [validateJWT, getUser] are async functions. Any suggestions on how to resolve this issue without compromising the linter guidelines by u ...

Filtering an array using Vue.js

I'm currently working on filtering an array using a computed property in vue.js. My goal is to search across multiple fields such as name, state, and tags. Here is my data: events: [ { id: 1, name: 'Name of event', url: &apos ...

Using Vuetify: adding an asterisk to indicate required fields

The most recent update of Vuetify (v1.3 - ) has brought a significant change. Now, the asterisk is no longer automatically added to the label when using v-textarea/v-text-field with the required prop.. You will need to include it manually in the label pro ...

Query to collect all user data using a WHERE clause

I recently started working with Firebase and have encountered an issue regarding the use of the 'where' clause. Here is a sample of the JSON data I'm dealing with: Users | |_____ John | |___ name: John Farmer | |___ searching ...

What is the best way to connect these functions in a sequence using promises?

A new software has been developed to extract data from an online t-shirt store and then organize the product information into a CSV file. The software consists of 3 scraping functions and 1 function for writing the data. I'm currently facing challen ...

Guide to smoothly animate dragging a component in React

I am having trouble dragging a component with CSS transform animation applied to it. The drag functionality doesn't seem to work properly as the component only moves based on the animation and cannot be dragged. Is there any solution to make the drag ...

Utilizing color schemes in your design: a step-by-step guide

Is there a way to utilize the custom color scheme defined in the theme export default createMuiTheme({ palette: { primary: { main: 'red', contrastText: '#ffffff' }, secondary: { main: 'green', ...

What is the best way to animate a 3D render based on scrolling with JavaScript?

My idea is to create a captivating animated 3D render that changes on scroll, much like the one featured on Apple's website. After inspecting the elements, it seems that this effect is achieved by using numerous images, each representing a specific fr ...

"Adding a Vue component into a contenteditable div: A step-by-step guide

Looking to develop a simple wysiwyg editor with Vue, I came across only one fully-fledged wysiwyg editor built on vue.js at https://quasar.dev/vue-components/editor. However, I couldn't find the ability to insert images there. Most other Vue wysiwyg e ...

What is the best approach to creating a user login page in Vue.js with axios integration?

As a junior frontend developer working with vue.js, my team lead has challenged me to replicate our company's web app login page. Despite having an account with the necessary credentials, I feel lost on where to begin. The only clue I have is that I n ...

Is there a method to implement colorPicker in an Angular WYSIWYG directive without utilizing jQuery?

After removing the jQuery reference, the color picker is no longer functioning in the WYSIWYG directive. In my project, I am avoiding the use of jQuery, so is there a way to achieve this without using jQuery? Alternatively, are there any other editors av ...

How can we link a specific ID with the correct user currently?

As a beginner with vue and firebase, I'm working on a project that does not have authentication. My goal is to create a simple site with multiple input fields on each page, a button to upload files, and a "Next page" button at the end of each page. To ...