Once the vuex persist plugin is implemented, I am encountering difficulties in accessing the store within the router

Ever since incorporating the vuex persist plugin, I've been encountering an issue where the store doesn't seem to be accessible in the router.

const vuexPersist = new VuexPersist({
    key: "vuex",
    storage: localStorage
});

const store = new Vuex.Store({
    state: {},
    modules: {
        alertStorage,
        userStorage,
    },
    //plugins: [vuexPersist.plugin] <-- if I comment out this, its working
});

In the router:

router.beforeEach((to, from, next) => {
    console.log(userStorage.state._user);
    next();
}

Interestingly, everything seems to work fine when that specific line is commented out:

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

However, once it's included:

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

Additionally, here's a glimpse at how my current store setup appears:

import {Module, Mutation, VuexModule} from "vuex-module-decorators";
import {UserResponseDto} from "@/common/dto/user-response-dto";
import Utils from "@/common/utils";

@Module
export default class UserStorage extends VuexModule{
     _user: UserResponseDto = {} as UserResponseDto;

    @Mutation
    protected loginUser(user: UserResponseDto) {
        this._user = user;
    }

    @Mutation
    protected logoutUser() {
        this._user = {} as UserResponseDto;
    }

    get isLoggedIn() {
        return !Utils.isEmpty(this._user);
    }

    get user():UserResponseDto{
        return this._user;
    }
}

Answer №1

It's completely normal for the behavior to be like this as you need to explicitly specify the localStorage of the current browser's window.

There are two approaches to make it work:

const vuexPersist = new VuexPersist({
    key: "vuex",
    storage: window.localStorage // updated here
});

Alternatively, you can omit specifying the storage altogether:

const vuexPersist = new VuexPersist({
    key: "vuex"
});

In the latter case, the default storage used is: window.localStorage.

In both scenarios, remember to add the plugin to your Vuex instance:

const store = new Vuex.Store({
    state: {},
    modules: {
        alertStorage,
        userStorage,
    },
    plugins: [vuexPersist.plugin] // Keep this line uncommented
});

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

What is the process for creating an additional username in the database?

As a beginner frontend trainee, I have been tasked with configuring my project on node-typescript-koa-rest. Despite my best efforts, I encountered an error. To set up the project, I added objection.js and knex.js to the existing repository and installed P ...

Transferring information between Vue.js components via data emissions

Greetings from my VueJS Table component! <b-table class="table table-striped" id="my-table" :items="items" :per-page="perPage" :current-page="currentPage" :fields="fields" @row-clicked="test" lg >< ...

Tips for transferring data between pages in VUE js using paths

I currently have two pages - an add page and an edit page. I am looking to transfer data from the edit page to the add page. When the save button is clicked in the edit page, it should redirect the user back to the add page with a URL of /test/admin/testin ...

How to use Vue to eliminate text from a title within an array

I am having trouble removing the text "this | " from the titles in an array. Can anyone suggest the most effective method to accomplish this? Any assistance would be highly appreciated :) Here is my JavaScript code: let Feed=require('rss-to-json&a ...

React fails to acknowledge union types

I have the following types defined: export enum LayersItemOptionsEnum { OPERATOR, HEADER, } type sharedTypes = { children: string | ReactElement; }; type LayersItemStatic = sharedTypes & { label: string; option: LayersItemOptionsEnum; }; t ...

Creating a nested type using template literal syntax

Given a two-level nested type with specific properties: export type SomeNested = { someProp: { someChild: string someOtherChild: string } someOtherProp: { someMoreChildren: string whatever: string else: string } } I am looking ...

Error: The module '@angular/core' cannot be located

Currently, I am working on a simple Angular 2 project with NodeJS as the backend and my preferred editor is Atom. So far, I have successfully installed Angular2 (2.0.0-beta.17) and Typescript using npm. npm install angular2 npm install -g typescript Wit ...

Loading data into the Nuxt store upon application launch

Currently, I'm working on an app using Nuxt where I preload some data at nuxtServerInit and store it successfully. However, as I have multiple projects with similar initial-preload requirements, I thought of creating a reusable module for this logic. ...

Developing a TypeScript NodeJS module

I've been working on creating a Node module using TypeScript, and here is my progress so far: MysqlMapper.ts export class MysqlMapper{ private _config: Mysql.IConnectionConfig; private openConnection(): Mysql.IConnection{ ... } ...

Invoke cloud functions independently of waiting for a response

Attempting a clever workaround with cloud functions, but struggling to pinpoint the problem. Currently utilizing now.sh for hosting serverless functions and aiming to invoke one function from another. Let's assume there are two functions defined, fet ...

The type 'contextPaneTitleText' argument cannot be assigned to the parameter type 'key of RemoteConfig'

I am encountering an issue when using the following code snippet: const contextPaneTitleText = useFeature("contextPaneTitleText").asString(); This code is resulting in an error message: Argument of type '"contextPaneTitleText" ...

Consolidating Typescript modules into a single .js file

Recently, I was able to get my hands on a TypeScript library that I found on GitHub. As I started exploring it, I noticed that there were quite a few dependencies on other npm packages. This got me thinking - is there a way to compile all these files int ...

I'm having trouble setting a value for an object with a generic type

I am attempting to set a value for the property of an object with generic typing passed into a function. The structure of the object is not known beforehand, and the function receives the property name dynamically as a string argument. TypeScript is genera ...

The disabled attribute appears to be ineffective in an Angular reactive form

In my Angular reactive form, I have an email field that I want to disable when the form is in edit mode instead of add mode. The code I am using for this is: disabled: typeof user.user_id === 'string' When I debug the modelToForm method and che ...

The implementation of Symbol.species in the Node.js Buffer class to generate a RapidBuffer seems illogical and confusing

While exploring the source code of ws, a popular WebSocket implementation for Node.js, I stumbled upon this specific piece of code: const FastBuffer = Buffer[Symbol.species]; But what exactly is this FastBuffer used for? Surprisingly, it seems that they a ...

Converting an array into an object by using a shared property in each element of the array as the key

I have an item that looks like this: const obj = [ { link: "/home", title: "Home1" }, { link: "/about", title: "About2" }, { link: "/contact", title: "Contact1" } ] as const and I want to p ...

Tips for releasing multiple versions of a plugin in parallel for an npm package

In my role as the caretaker of a library called MyLib currently available on npm as a vuejs plugin, I am facing challenges with the recent major version release of vuejs. Initially developed when vuejs was at version 2.x.x, the latest iteration now support ...

Modify 2 URL parameters using the entered text and selection

Is there a way to dynamically update parameters in the URL of my service using input text and select options? Current URL: http://localhost/?population/?article=code&year=value I am looking for a solution to set the 'code' parameter through ...

Angular 2 Login Component Featuring Customizable Templates

Currently, I have set up an AppModule with a variety of components, including the AppComponent which serves as the template component with the router-outlet directive. I am looking to create an AuthModule that includes its own template AuthComponent situa ...

Avoiding caching when making requests to /api/ routes in VueJS Progressive Web Apps (PWA

I recently developed a Vuejs project with PWA capabilities, but encountered an issue when building its production version. The project seems to be using cached versions of API requests instead of making fresh network calls. I am trying to find a way to eit ...