I'm having trouble understanding the functionality of getters in Vuex. The issue arises when I log out the token and find that the state and localStorage are empty, but the getters still contain the old token value.
In the created
lifecycle hook, I have the following code:
created: async function () {
if (this.$store.getters.shortToken) {
this.isConfirm = true
}
console.log(
'signining', localStorage.getItem('token'), // ''
'state', this.$store.state.user.token, // ''
'getter', this.$store.getters.token // 'old-token'
)
if (this.$store.getters.token) {
await this.$router.push({ path: '/' })
}
}
The getters
section contains:
token: state => {
return localStorage.getItem('token') || state.user.token
}
And for the mutation
:
SET_TOKEN: (state, payload) => {
localStorage.setItem('token', payload.token)
Object.assign(state, payload)
}
However, the console log within created shows an empty localStorage token (expected behavior), empty state.token (also expected).. But, getters.token displays the token value (unexpected), despite setting SET_TOKEN with an empty token. Why is this happening?
PS. If I add a
console.log(state.user.token, localStorage.getItem('token'))
above the return
statement in the getters token, the getters.token
in the created
hook becomes empty... WHY?
Here are some relevant codes for handling this scenario, starting with the logout method:
methods: {
async logout () {
if (await this.$store.dispatch('logOut')) {
console.log('logged out')
await this.$router.push({ path: '/signin' })
}
}
}
Action for logging out
async logOut (context) {
console.log('logggog')
context.commit('SET_TOKEN', {
token: ''
})
context.commit('SET_USER', {
user: null
})
return true
}