I need to display different buttons in the Header component based on the user's authentication status.
Header.vue
<template>
<div class="utf_right_side">
<div class="header_widget">
<router-link :to="{name:'login'}" class="button border sign-in popup-with-zoom-anim" v-if="!isAuth"><i class="fa fa-sign-in"></i>Login</router-link>
<a class="button border sign-in popup-with-zoom-anim" v-if="isAuth" href="" @click.prevent="logout" :key="componentKey"><i class="fa fa-sign-in"></i>Logout</a>
<a href="dashboard_add_listing.html" class="button border with-icon"><i class="sl sl-icon-user"></i> Add Listing</a></div>
</div>
</template>
<script>
import {mapActions} from 'vuex'
export default {
name:"default-layout",
data(){
return {
user:this.$store.state.auth.user,
isAuth: this.$store.state.auth.authenticated,
}
},
methods:{
...mapActions({
signOut:"auth/logout"
}),
async logout() {
await axios.post('/logout').then(({data})=>{
this.signOut();
this.$parent.forceRerender();
})
},
},
}
</script>
The isAuth
variable from the Vuex state determines which buttons are displayed. However, after logging in, the state remains unchanged and displays the old button instead of the authenticated one. A manual page refresh (F5) correctly shows the authenticated button.
Login.vue:
<script>
import { mapActions } from 'vuex'
export default {
name:"login",
data(){
return {
auth:{
email:"",
password:""
},
validationErrors:{},
processing:false
}
},
methods:{
...mapActions({
signIn:'auth/login'
}),
async login(){
this.processing = true
await axios.get('/sanctum/csrf-cookie')
await axios.post('/login',this.auth).then(({data})=>{
this.signIn()
}).catch(({response})=>{
if(response.status===422){
this.validationErrors = response.data.errors
}else{
this.validationErrors = {}
alert(response.data.message)
}
}).finally(()=>{
this.processing = false
})
},
}
}
</script>
Vuex auth.js included in index.js Vuex file:
import axios from 'axios'
import router from '@/router'
export default {
namespaced: true,
state:{
authenticated:false,
user:{}
},
getters:{
authenticated(state){
return state.authenticated
},
user(state){
return state.user
}
},
mutations:{
SET_AUTHENTICATED (state, value) {
state.authenticated = value
},
SET_USER (state, value) {
state.user = value
}
},
actions:{
login({commit}){
return axios.get('/api/user').then(({data})=>{
commit('SET_USER',data)
commit('SET_AUTHENTICATED',true)
router.push({name:'home'})
}).catch(({response:{data}})=>{
commit('SET_USER',{})
commit('SET_AUTHENTICATED',false)
})
},
logout({commit}){
commit('SET_USER',{})
commit('SET_AUTHENTICATED',false)
}
}
}
When a user logs in, the login method in auth.js sets the correct state as shown here:
commit('SET_USER',data)
commit('SET_AUTHENTICATED',true)|
Even after being redirected to the home route, the Header still displays the old button. Only a manual page refresh correctly shows the authenticated button.