The Vue router is unable to access the store state

My Vue application is utilizing vue-router and vuex. I acquire an authentication token from my API, store it in localStorage, and then push it to the store. However, when the page refreshes, the app is unable to retrieve the token from localStorage and the store remains empty. To handle authorization, I have implemented a guard in my router:

router.beforeEach((to, from, next) => {
    if (to.matched.some(record => record.meta.auth)) {
        if (store.getters.logged) {
            if (to.meta.scope === store.getters.scope){
                next();
                return;
            }else{
                next({name: 'forbidden'});
                return;
            }
        }
        next({name: 'login'});
    } else {
        next();
    }
});

Unfortunately, the guard is not functioning correctly due to vue-router loading before vuex, causing the store to be empty and the scope to be undefined. As a result, all requests are redirected to the forbidden route. How can I resolve this issue?

Answer №1

It appears that the issue lies in the implementation of storing and retrieving data from localStorage. My recommendation is to avoid reinventing the wheel and utilize this package, which offers a solution to your problem:
https://www.npmjs.com/package/vuex-persistedstate

import createPersistedState from 'vuex-persistedstate'

const store = new Vuex.Store({
  // ...
  plugins: [createPersistedState()]
})

Answer №2

To enhance your application's functionality, consider importing the store before the router as demonstrated below:

import Vue from 'vue';
import router from './router';
import store from './store';
import App from './App.vue';

new Vue({
    store,
    router,
    render: (h) => h(App)
}).$mount('#app');

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

Divide using two separators

const inputString = 'db.employee.find({"city":"Paris"},{"emp_id":1}' const result = inputString.split(/\.|\[); // splitting based on . or [ Is there a way to split a string based on two delimiters, such as . and [? For example, if we ...

The PHP code encountered a syntax error due to an unexpected $EOF on the final empty line

I've been tasked with maintaining an old website that went offline due to script errors. I managed to resolve most of the issues in the script, but there's one error that's giving me trouble. The site is showing a syntax error that says "une ...

Vue component props are coming back as undefined

I've been struggling for two days to fix this issue on my own, but I just can't seem to get it working. The problem is that even though I declared all my props in the parent component, they're not showing up for some reason. Code Snippet ...

Integrating fresh components into a JSON structure

I've been attempting to insert a new element into my JSON, but I'm struggling to do it correctly. I've tried numerous approaches and am unsure of what might be causing the issue. INITIAL JSON INPUT { "UnitID":"1148", "UNIT":"202B", "Sp ...

Tips for closing the stdio pipes of child processes in node.js?

Looking to spawn a child process from node.js and monitor its stdout before closing the pipe to terminate the node process. Here's my base code snippet that is currently not ending the node process: const childProcess = require("child_process"); con ...

Can a sophisticated text editor be utilized without a content management system?

Many website builders utilize rich text editors as plugins to enhance content creation, such as in CMS platforms like Joomla and WordPress. However, can these same editors be easily integrated into a custom website built from scratch using just HTML, PHP ...

How can I trigger a success event in JavaScript after ASP.NET form validation?

Is there a way for me to be notified when my ASP.NET form validation is successful so I can subscribe to that event? Here's the situation: When a user clicks a button on a payment form, I want to display a message saying "processing," but only if the ...

What could be the reason for this simple sails socket not functioning properly?

Just curious why the simple web socket code below isn't functioning? io.socket.on('user', function(event){ console.log("RECEIVED EVENT:",event); }) I have included sails.io.js in my index file and the above code is located in a test.js ...

AngularJS $cookies version 1.6.9 experiencing functionality issues

I recently implemented AngularJS $cookies 1.6.9 in my website to handle cookie management. To test it out, I attempted a basic cookie set like this: $cookies.put('myCookieTest', 'test'); var cookie = $cookies.get('myCookieTest&apo ...

Tips for sorting through JSON Data to isolate a particular day

I developed a Food-App that displays a different menu every day. I retrieve the local JSON Data using Axios and attempt to filter the mapped menu with .filter. My issue lies in not being able to filter specific days. I attempted to restructure the JSON Da ...

Searching for the most recent entry from a related group within an HTML table using jQuery

I have a list of students in different classes that looks like this Class StudentName RollNo. Class X Sarah 1 Class Y David 2 Class Z Emily 3 Class W Adam 1 C ...

There seems to be an issue with .ENV functionality in Razzle JS

Attempting to deploy a Razzle project on an Ubuntu server has been challenging. I have created a .env file with two variables: port=80 and host=192.168.1.5. However, when running the project, it defaults to localhost:3000. I've tried exporting PORT=80 ...

Exploring Unicode Symbols for Icon Selection

I'm currently working on integrating an icon picker into my application that will enable the user to select a mathematical operator for data comparison. While I have successfully implemented the fontawesome-iconpicker on the page, I am encountering d ...

Node.js API requests often result in undefined responses

As a newcomer to Node.JS, I am currently experimenting with calling a REST API using the GET method. I have utilized the 'request' package available at this link. While the call functions correctly, I encounter an issue when attempting to return ...

Dynamic component list using Vue-loader

I've recently started working with Vue.js and I've encountered a problem that I believe should have a straightforward solution: I have a single file component (.vue) that needs to display and manage a dynamic list of another single file component ...

Placing an image on a three.js cube using overlay does not function properly

I attempted to superimpose an image onto a cube by utilizing code from GPT chat and Blackbox AI, but in both cases, I encountered a black screen. I saved the code in a file named test.html and tested it on Google Chrome and Opera GX browsers, only to be me ...

Fetching server-side data for isomorphic React app: A guide to accessing cookies

Currently, I am in the process of developing an isomorphic/universal React + Redux + Express application. The method I use for server-side data fetching is quite standard: I identify the routes that match the URL, call the appropriate data-fetching functio ...

How can a row in AG-Grid be updated without causing a refresh?

I am working on adding a custom radio button feature for users to select a row. Currently, I have the following code: const Cell = (cellProps) => { const { data, node, api } = cellProps const selectedRow = () => { let { isChecked } = data ...

What is the process of obtaining the ID and displaying the subsequent field based on that ID in Ruby on Rails?

I'm utilizing rails4 and I am looking for a more efficient way to display the sub-category list based on the category selected in a form. Currently, I have used JavaScript for this functionality but I believe there may be a better solution. Any sugges ...

Ways to manage the order of RequestExecutor execution

I have recently developed an intranet site using SharePoint Office 365. Within the master page file, there is a menu bar that utilizes a List to store the URL and name. My goal is to control the visibility of the "Admin" button based on whether the user ...