Describing how to assign multiple variables in a VUEX mutation

store.js

import Vue from 'vue';
    import Vuex from 'vuex';
    import userStore from './user/userStore.js';
    import VuexPersist  from "vuex-persistedstate";
    Vue.use(Vuex)
    const debug = process.env.NODE_ENV !== 'production'

    const vuexLocalStorage = new VuexPersist({
    key: 'vuex',
    storage: window.localStorage,
    })

    export default new Vuex.Store({
        modules:{
            userStore,
            plugins: [vuexLocalStorage.plugin]
        },

        strict:debug
    })
    

userStore.js

const state = {
        authUser:null,
        roles:null
    }
    const mutations  = {
        SET_AUTH_USER(state,userObj){
            state.authUser = userObj
        },
        SET_USER_ROLE(state,userRole){
            state.roles = userRole      
        }
    }
    const actions = {
        setUserObject :({commit},userObj) => {
            commit('SET_AUTH_USER',userObj)
        },
        setUserRoles :({commit},userRole) => {
            commit('SET_USER_ROLE',userRole)
        }
    }
    export default {
        state, mutations, actions
    }
    

Sidebar.vue

created(){
        this.getRoles();
    },
    methods: {
        getRoles(){
            var _this = this
            _this.roles_data = response.data
            _this.$store.dispatch('setUserRoles',_this.roles_data)
            _this.fetch_roles()
        }
        fetch_roles(){
            console.log(this.$store.state.userStore.roles)
            // OUTPUT
            // (3) [{…}, {…}, {…}, __ob__: Observer]

            console.log(this.$store.state.userStore)
            // OUTPUT
            // {__ob__: Observer}
            // authUser: "NqStDm8ol3QGtoh0hzL7yhC3NP3HV0ktYKmYHI8TNiCjG4T4tLlv3pOEWFdA5CEh"
            // roles: Array(3)      
        }
    }
    

Dashboard.vue

created(){
        console.log(this.$store.state.userStore.roles)
        // OUTPUT
        // null

        console.log(this.$store.state.userStore)
        // OUTPUT
        // {__ob__: Observer}
        // authUser: "NqStDm8ol3QGtoh0hzL7yhC3NP3HV0ktYKmYHI8TNiCjG4T4tLlv3pOEWFdA5CEh"
        // roles: Array(3)
    }
    

hi I am working on managing user roles access in a Vuex store. The store contains two variables: 1) authUser 2) roles. The authUser stores the user token and roles stores an array of user roles. When fetching roles from the API, I dispatch the roles using _this.$store.dispatch('setUserRoles',_this.roles_data). In the sidebar component, when I log the output, I get:

console.log(this.$store.state.userStore.roles)
    (3) [{…}, {…}, {…}, __ob__: Observer]

    console.log(this.$store.state.userStore)
    {__ob__: Observer}
    authUser: "NqStDm8ol3QGtoh0hzL7yhC3NP3HV0ktYKmYHI8TNiCjG4T4tLlv3pOEWFdA5CEh"
    roles: Array(3)
    

However, when I do the same logging in the created function of the dashboard component, it returns roles as null.

console.log(this.$store.state.userStore.roles)
    null

    console.log(this.$store.state.userStore)
    {__ob__: Observer}
    authUser: "NqStDm8ol3QGtoh0hzL7yhC3NP3HV0ktYKmYHI8TNiCjG4T4tLlv3pOEWFdA5CEh"
    roles: Array(3)
    

Am I overlooking something? Or is there a bug?

Answer №1

First and foremost, ensure that the plugin declaration is placed outside the modules block, rather than within it.

Your current setup looks like this:

export default new Vuex.Store({ modules:{
    userStore,
    plugins: [vuexLocalStorage.plugin] },

However, it should be organized as follows:

export default new Vuex.Store({
  modules:{
    userStore
  },
  plugins: [vuexLocalStorage.plugin]
}

Next, make sure you specify the store module path to persist in the vuex-persistedstate plugin.

If this declaration is missing, include it in the following manner:

const vuexLocalStorage = new VuexPersist({ 
    paths: ['userStore'], //an array of the name of your store modules you want to persist
    key: 'vuex', 
    storage: window.localStorage 
})

You may also need to set your module as namespaced, for example:

const namespaced = true 

const state = {
    authUser:null,
    roles:null 
} 
const mutations  = {
    SET_AUTH_USER(state,userObj){
        state.authUser = userObj
    },
    SET_USER_ROLE(state,userRole){
        state.roles = userRole      
    }
}
const actions = {
    setUserObject :({commit},userObj) => {
        commit('SET_AUTH_USER',userObj)
    },
    setUserRoles :({commit},userRole) => {
        commit('SET_USER_ROLE',userRole)
    }
}
export default {
    namespaced,
    state, 
    mutations, 
    actions
}

Consider using js-cookies instead of localStorage for security reasons by implementing it as shown below:

import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import userStore from '/path/to/userStore'
import * as Cookies from 'js-cookie'

export default new Vuex.Store({
    plugins: [
        createPersistedState({
            paths:['userStore'],
            storage: {
                getItem: key => Cookies.get(key),
                setItem: (key, value) => { 
                    Cookies.set(
                        key, 
                        value, 
                        { expires: new Date(new Date().getTime() + 20 * 60 * 1000) })
                },
                removeItem: key => { 
                    Cookies.remove(key)
                    localStorage.removeItem('vuex')
                }
              }
            }
        )],
    modules:{
        userStore
    }
})

To access the persisted key from Cookies, use the following method:

JSON.parse(Cookies.get("vuex")).userStore

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

Disregard any unrecognized variables associated with the third-party package

I've been working on integrating the bluesnap payment gateway into a react/ts project. I added their hosted javascript code to my public/index.html and started the integration within a component. However, when compiling, an error pops up saying ' ...

Error message: "Issue with Jointjs library on Node.js server - Uncaught ReferenceError: Joint is not recognized"

I am attempting to create a sample diagram using the code below on a file hosted on a Node server: <!DOCTYPE html> <html> <head> <title>newpageshere</title> <link rel="stylesheet" href="joint.css" /> <script src="j ...

Are there any available npm modules for accurately tallying the total word count within a document saved in the .doc or .doc

I Need to tally the number of words in doc/docx files stored on a server using express.js. Can anyone recommend a good package for this task? ...

Troubleshooting Limitation Problem with Bootstrap Multiselect

I recently created a multiselect dropdown menu using Bootstrap Multiselect. I successfully set a limit on the number of options that can be selected (in this case, 5), and once the limit is reached, the additional options become disabled. Everything works ...

How can I increase the size of the nuka-carousel dots in React/Nextjs?

Looking for help on customizing the size of dots in my nuka-carousel. Unsure how to change their sizing and margin. ...

Retrieve the subdomain from within the passport FacebookTokenStrategy and GoogleStrategy

In the process of developing a node.js application with wildcard subdomains, I am creating separate parts of the app for each subdomain that will have distinct user authentication based on the subdomain. For instance, envisioning my app having subdomains ...

Perl's powerful capabilities allow for the creation of interactive drop-down menus

As a newcomer to web programming, I have recently been tasked with scripting projects during my summer internship. I've been utilizing Perl to develop CGI scripts for my company's internal website, specifically catering to the needs of the develo ...

React-Bootstrap Table Toolkit Encounter Search Import Issue

I encountered an issue while trying to integrate React Bootstrap Table into my project, resulting in the following error message. Uncaught ReferenceError: arguments is not defined at Object../node_modules/react-bootstrap-table2-toolkit/lib/src/search/Sea ...

Does the entire state get replaced every time a change is made if the state is immutable?

Is it necessary to replace the entire state if it is immutable? Otherwise, wouldn't mutating the state occur? Are top-level keys maintained as distinct immutable objects? Wouldn't changing anything necessitate replacing the entire state by defin ...

Accessing Data from Nested PHP Array in Javascript

My current situation is this: I have a MYSQL database that consists of two fields: 'ID' and 'string'. The 'string' field stores serialized arrays. To extract the data back, I utilize the following PHP code: $result = mysql_q ...

Steps for transforming 112889 (in mmddyy format) into 11/28/89 or 11/28/1989

Is there a way to convert the unformatted date 112889 (mmddyy) into a specific format like 11/28/89? console.log(new Date('112889')) // The output I'm getting is: Sat Jan 01 112889 00:00:00 GMT+0800 I've searched extensively on Google ...

Best practices for effectively dismantling a Paper.js Scope

In my web project, I am utilizing multiple Paper.js canvases by creating a new scope for each of them. Due to the AJAX-driven nature of the site, I need to get rid of unnecessary instances when switching between subpages. Unfortunately, there is no built-i ...

Initializing an Express app with JSON file loading

My movie-finding application relies on backend API calls to function. As part of the initialization process, I need to load two JSON files: one containing a list of languages for searching (lang.json) and another stored in the config variable that provides ...

The v-select function organizes data based on the content of "item-text"

I created a v-select component using Vuetify, and I am wondering how I can sort the names of the items from largest to smallest within this v-select? <v-select v-model="selectedFruits" :items="fruits" label="Favorite Fruit ...

What is the maximum amount of information that can be stored in a data attribute within the DOM?

Occasionally, I find myself wanting to include a substantial amount of data on the webpage in order to minimize additional AJAX calls for dynamic content. However, I am concerned about potential performance implications. Is there a penalty I should be aw ...

Utilize Google Tag Manager to search and substitute characters within a variable

Within my GTM setup, I have a CSS selector variable in the DOM. This variable pertains to real estate and specifically represents the price of a listing. My goal is to eliminate the characters ($) and (,) from this variable as part of meeting the requireme ...

The 404 error message was encountered when attempting to fetch the Ajax

I am experimenting with using Ajax to load all images from a local folder onto my HTML page. The code I am referring to comes from this question. I am running the files on a (Tomcat 8.5) server in Eclipse and opening the URL in Google Chrome. However, when ...

Struggling to get collapsible feature functioning on website

I'm trying to create a collapsible DIV, and I found a solution on Stack Overflow. However, I'm having trouble getting it to work on my website. I created a fiddle with the full code, and it works there. But when I implement it on my site, the con ...

Styling Javascript Objects

[ [ {"path":"path2","value":"kkk"}, {"path":"path0","value":"uuu"}, {"path":"path1","value":"ppp"} ] ] The result obtained from my manipulation is shown above. However, I require the format to be as depicted below: ["path":"pat ...

Encountered an error: Object(...) does not conform to function standards in the handleChange method

When using JavaScript, everything works fine. However, when trying to implement TypeScript with the handleChange function, an error is consistently thrown whenever something is typed into the entries. The error message reads: "TypeError not captured: Objec ...