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

Access different elements of an array by specifying custom start and end points

Is there a way to iterate over a JSON array with specified start and endpoints? For example, let's say we have a list of 20 items... I am looking to loop through the list in segments of 0-4, 5-9, 10-14, 15-19... I have attempted using the v-for sy ...

The jQuery onchange function does not have the ability to limit the input to only

When using the script to sum the input value, everything seems to be working fine. However, I am facing an issue where clicking up and down on the "input#total_selfmark" does not change the value. Additionally, when I manually type in a number, the "input# ...

The JWT Cookie has successfully surfaced within the application tab and is now being transmitted in the request

When sending a JWT token to an authorized user in Express, the following code is used: The cookie-parser module is utilized. module.exports.getUser = async (req, res, next) => { console.log('i am in getuser'); const { SIT } = req.query; ...

How can I retrieve the total number of records (count) in an XML response using PostMan?

Hello, I'm currently attempting to determine the length of an XML response but I'm running into some issues. The error message I am encountering is as follows: "There was an error in evaluating the test script: ReferenceError: xml2json is not def ...

What is causing the issue with using transition(myComponent) in this React 18 application?

Recently, I have been immersed in developing a Single Page Application using the latest version of React 18 and integrating it with The Movie Database (TMDB) API. My current focus is on enhancing user experience by incorporating smooth transitions between ...

Streamline uploading files with AngularJS using Selenium

I am utilizing Powershell to operate .NET Selenium with a FirefoxDriver in order to automate certain tasks. One of these tasks involves file uploads, and the website I am working with appears to have been built using AngularJS. After some experimentation, ...

Vue fails to retrieve the accurate value of the option, instead displaying the text

Just started using Vue.js through CDN. Currently working with a select element: <select @change="setValue($event.target.value)"> <option>Pick</option> <option val="1">First Choice</option> <opt ...

Utilize Haxe Macros to swap out the term "function" with "async function."

When I convert haxe to JavaScript, I need to make its methods asynchronous. Here is the original Haxe code: @:expose class Main implements IAsync { static function main() { trace("test"); } static function testAwait() { ...

Updating a property value within a JSON object: Adjusting attributes in a JSON data format

How can I modify a specific key's value in a JSON array like the following example: input = [{"201708":10,"201709": 12, "metric":"attritionManaged"},{"201708":10,"201709": 12, "metric":"attritionUnManaged"},{"201708":10,"201709": 12, "metric":"EHC"}] ...

I wonder what the outcome would be if I used res.send to send a JSON file instead of res.json

Is it possible to send a JSON file using res.send in NodeJs instead of res.json? What are the potential consequences of doing this and why is it recommended to avoid this practice? ...

Tips for resolving the 'route.search' bug in Express.js

I recently started working on a basic Express app (with Node) and I am in the initial setup phase. However, I have encountered an error that is proving to be quite challenging to resolve. Despite my attempts to search for solutions online and browse throu ...

Is there a way to pass locale data using props in VueJS Router?

To access hotel data, the URL path should be localhost:8080/hotel/:id (where id is equal to json.hoteID). For example, localhost:8080/hotel/101 This path should display the specific data for that hotel. In order to achieve this, we will utilize VueJS vu ...

In my programming world, 'i' is a mysterious being - always undefined, except when it decides

Currently, I am utilizing Vue, Vuedraggable, and Vuetify in my project. I have encountered an issue where I am unable to use 'let' to define the index for my loop as it always returns undefined. Strangely, using 'var' instead of ' ...

Passing parameters to JavaScript onload event from PHP

Looking for help with integrating date data from PHP into a JavaScript countdown function. I have extracted the date from a database using PHP, but struggling to pass it correctly to the JavaScript function. My attempt so far: <body onload="countIt(< ...

Querying MongoDB with a JavaScript file for formatting datetime values

I am utilizing mongodb3.0.5 and my database collection appears as follows: { "_id" : "xxxxxxxxxxxxxxx", "SchoolId" : 1, "ActivationTimestamp" : ISODate("2015-09-22T13:01:58.000Z"), "PersonDetails" : [ { "Name" : "John" ...

When using Vue.js and Quasar to implement multiple filtering forms, an issue arises where the input value disappears

I am currently exploring how to implement multi-item filtering in Quasar, a framework of Vue. At the moment, I am utilizing input and checkbox elements. Everything seems to be functioning correctly, but there is an issue with the select item disappearing. ...

utilizing the active class with react js

Apologies for the question, but I am facing an issue where adding an active class to a button is affecting all buttons when clicked. How can this be fixed? Here is the code snippet: <div className=""> {category.items.length === 0 ? ( ...

history.push() function is ineffective within a JavaScript file that does not contain a class

I've been delving into React and encountering an issue with the history.push("/dashboard") method, it's not functioning as expected. import axios from "axios"; import { GET_ERRORS, GET_PROJECT, GET_PROJECTS } from "./types"; export const createP ...

Translate a jQuery ajax request utilizing jQuery().serialize into plain JavaScript

Currently, I've been in the process of converting a jQuery script into vanilla JavaScript to completely eliminate the need for jQuery. The main functionality of the code includes: Upon clicking a button on the front end, an ajax request is sent, upda ...

What is the process for retrieving data through a server-side API request?

I have been working on setting up my API URL in my Node.js backend application. I initially passed the entire URL in my frontend AJAX call, but now I want to transition to a server-side API call to avoid exposing the URL. Since I am not very experienced wi ...