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?