Currently I have the following configuration in my vuex, what I do is through the userAuth action verify the user's role and assign it to a property of the state 'rol_user'
, using the UPDATEROL
mutation. I execute this action when I log in so that the user's role is recorded in vuex.
here the vuex configuration:
import Vue from "vue";
import Vuex from "vuex";
import firebase from 'firebase';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
rol_user: ''
},
mutations: {
UPDATEROL: function (state, payload) {
state.rol_user = payload.rol_user;
}
},
actions: {
userAuth: async (context) =>{
let user = firebase.auth().currentUser;
if(user){
let user_info = await firebase.database().ref('users').child(user.uid).once('value');
let val_user = user_info.val();
console.log("USER AUTH - VUEX");
console.log(val_user.rol);
context.commit('UPDATEROL',{
rol_user: val_user.rol
});
}
}
}
});
It effectively assigns the user's role to the state
property, rol_user
.
The problem I have is when reloading the page. When I reload the page rol_user
returns to its initial state, that is empty.
How can I do so that the value of the role is not lost even when reloading the page, but rather that it is changed to empty only until I log out
You need to use some sort of storage mechanism and check that storage everytime the app is first mounted. For example, you could store a session key in localStorage
or just store the user state that you want to persist.
Note, I do not know what kind of data you are storing, I am assuming rol_user
is an object, if it is a string, you do not need JSON serialization/deserialization as I've done in the example below:
import Vue from "vue";
import Vuex from "vuex";
import firebase from 'firebase';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
rol_user: ''
},
mutations: {
UPDATEROL: function (state, payload) {
state.rol_user = payload.rol_user;
localStorage && (localStorage.rol_user = JSON.stringify(state.rol_user));
//^ try to store the user role in localStorage
},
},
actions: {
userAuth: async (context) =>{
if(localStorage && localStorage.rol_user) {
//^ if it's in localStorage, log the user back in/update state to match what it is in localStorage
context.commit('UPDATEROL', { rol_user: JSON.parse(localStorage.rol_user)});
return;
}
let user = firebase.auth().currentUser;
if(user){
let user_info = await firebase.database().ref('users').child(user.uid).once('value');
let val_user = user_info.val();
console.log("USER AUTH - VUEX");
console.log(val_user.rol);
context.commit('UPDATEROL',{
rol_user: val_user.rol
});
}
}
}
});
You could also use Cookies (cookies are generally more common for this purpose, but localStorage also works just fine)