- I use vuex for state management and authenticate users with firebase
- I use vuex-persisted state to save the state in cookies
In my vuex store I manage my userdata(user name , logged in status) as below
my store.js
/all imports here
export const store = new Vuex.Store({
state : {
user: {
loggedIn: false,
userName: 'Guest'
}
},
getters : {
g_user: state => {
return state.user;
}
},
mutations : {
m_logInUser: (state, userName) => {
state.user.loggedIn = true;
state.user.userName = userName;
},
m_loggedOut: (state) => {
state.user.loggedIn = false;
state.user.userName = 'Guest';
}
},
actions : {
a_logInUser: ({state, commit}, userInput) => {
//call to the API and on success commit m_logInUser mutation
},
a_loggedOut: ({commit}) => {
//call to the API and on success commit m_loggedOut mutation
}
},
plugins: [
createPersistedState({
paths: ['authStore.user'],
getState: (key) => Cookie.getJSON(key),
setState: (key, state) => Cookie.set(key, state, { expires: 3, secure: false })
})
]
});
now the problem I am facing
when I open the app in two different tabs and login the user in 1st tab , the user logs in which now hides the login buton and shows logout button and shows the username
but in the 2nd tab its still showing the login button , but when i console.log for the user, it shows logged in and also the username
here is my header.vue component
<template>
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<router-link to="/" tag="a" class="navbar-brand">Brand</router-link>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li @click="testmethod"><a>cuser</a></li>
<router-link to="/statuses" active-class="active" tag="li"><a>Status</a></router-link>
<router-link to="/users" active-class="active" tag="li"><a>Users</a></router-link>
</ul>
<ul class="nav navbar-nav navbar-right" v-if="!g_user.loggedIn">
<router-link to="/signup" active-class="active" tag="li"><a>Signup</a></router-link>
<router-link :to="{name: 'login'}" active-class="active" tag="li"><a>Login</a></router-link>
</ul>
<ul class="nav navbar-nav navbar-right" v-else>
<router-link to="/post" tag="li"><a><button class="btn btn-info">POST</button></a></router-link>
<router-link to="/current" active-class="active" tag="li"><a>{{ g_user.userName }}</a></router-link>
<li @click="logOut"><a>Log out</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
</template>
<script>
import { mapGetters } from 'vuex'
export default{
methods: {
logOut(){
this.$store.dispatch('a_loggedOut');
},
testmethod(){
var user = this.$firebase.auth().currentUser;
console.log(user);
console.log(user.email);
}
},
computed: {
...mapGetters([
'g_user'
])
}
}
</script>