Getter is not updated in computed


#1
##################################
const state = {
user: {
token: localStorage.getItem(‘user-token’) || ‘’
}
}

## ########################
const mutuation = {
  SET_TOKEN(state, token){
  localStorage.setItem(‘user-token’, token)
  },
  REMOVE_TOKEN(state){
  localStorage.removeItem(‘user-token’)
  },
}

## 
const actions = {
login({commit}, data){
commit(‘SET_TOKEN’, token)
axios.defaults.headers.common[‘Authorization’] = token
router.push(’/’)
},
logout({commit}){
commit(‘REMOVE_TOKEN’)
delete axios.defaults.headers.common[‘Authorization’]
router.push(’/’)
}
}

## 
const getters = {
isAuthenticated: state => !!state.user.token
}

My problem is, after i call login/logout, my token in state was changed, But when i use mapGetter isAuthenticated in computed, this return value’s not fit with value in State:

....
<div v-if="isAuthenticated">
  <a @click='logout()' class="dropdown-item">Logout</a>
</div>
<div v-else>
  <router-link to="/login" class="dropdown-item">Login</router-link>
  <router-link to="/register" class="dropdown-item">Sign up</router-link>  
</div>
......
<script>
  computed:{
    ...mapGetters( 'user', [
      'isAuthenticated'
    ])
  },
  methods: {
    ...mapActions('user', [
      'logout'
    ]),
  }
<script>

#2

Please format your post. Using Syntax Highlighting in this forum

Please provide the related component code


#3

Sorry my mistake, I’ve edited my topic.


#4

LocalStorage is not reactive. Your vuex state will not change just beause you changed the localStorage.

So you also have to set/unset the token in the state.


#5

Oops! thank you so much. I don’t relize that. My problem solved