Search code examples
vue.jsvuejs2vuex

vuex store token doesn't update accross components


I have the following store/index.js file:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const state = {
  token: null
}
const mutations = {
  setToken (state, token) {
    state.token = token
    localStorage.setItem('token', token)
  },
  removeToken (state) {
    state.token = null
    localStorage.removeItem('token')
  }
}
const getters = {
  isLoggedIn: state => {
    return state.token != null
  }
}
export default new Vuex.Store({
  state,
  getters,
  mutations
})

and in my main.js I add it as such:

import store from './store'

new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})

and when I login I set the token as such:

this.$store.commit('setToken', response.data.token)

Which should be working because the setToken function successfully save it to localStorage.

However, if I go to my other components and call:

data () {
  return {
    loggedIn: false
  }
},  
mounted: function () {
  this.loggedIn = this.$store.getters.isLoggedIn
  console.log(this.loggedIn)
}

then console will print 'false'. I have also tried to change 'mounted' to 'computed', 'created' and 'ready' but the result is the same.

I can only seem to solve the problem if I do like this:

mounted: function () {
  this.token = localStorage.getItem('token')
  this.$store.commit('setToken', this.token)
},
computed: {
  isLoggedIn () {
    return this.$store.getters.isLoggedIn
  }
}

for which isLoggedIn will finally be true.

But if I do like that then what's the point of vuex..

I'm thinking I either do something wrong with not knowing whether to call computed/mounted/etc, or maybe the way I do mutations is wrong, or maybe I don't initialize Vuex in the proper file.. but I feel like I've tried it all now


Solution

  • Your component is probably mounted before you login and set the token.

    Seeing as you're using local storage for token persistence, I would initialise the value that way, ie

    const state = {
      token: localStorage.getItem('token')
    }
    

    This will be null if it has not been set (or has been removed).