Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS - how to watch a value in localStorage?

Tags:

vuejs2

I have a nav component that needs to only be shown when there is a token stored in localStorage. When that token is deleted from localStorage the nav component needs to notice that change and hide itself.

What's the best way to approach this?

like image 489
Garfonzo Avatar asked Dec 06 '25 03:12

Garfonzo


2 Answers

Local Storage is not reactive, so you need to store your token in some place that is. I assume your token is being set and deleted by the application. If so, the best way to handle this is to use state like Vuex (see Vue State Management).

Option 1

If you are using local storage in order to retain the token between multiple browser sessions, the best option is to just set the token in Vuex then use Vuex persisted state to sync Vuex to local or session storage. The plugin will retrieve it again when you need to re-establish state.

Option 2

If you need it set in the local storage directly, you should include in your mutations to set/unset the localStorage when you are changing the state. This will keep your localStorage and State in sync.

For example using Vuex, if you are receiving a token in a response you can then call a Mutation to set it in Vuex state as well as set it to localStorage:

SET_TOKEN(state, payload){
    state.token = payload.token 
    localStorage.setItem('token', payload.token)
}

You can then easily watch the Vuex state. Depending on how your Vuex is set up, it may be something like: this.$store.state.token

like image 179
For the Name Avatar answered Dec 09 '25 16:12

For the Name


Hiding your navbar should not be related with setting localStorage. I would expect something like this:

function hideNav() {
  // Inform the application that the nav should hide
  dispatchHideNavAction() 

  // Change localStorage
  deleteTokenFromLocalStorage()
}

If instead, your problem is in hiding the nav when the token is deleted from another window, then you can use StorageEvent:

window.addEventListener('storage', (e) => {
  if (e.key === 'mytoken' && e.newValue === null) {
    hideNav()
  }
});

NB: this won't work within the same window, but only if the token is deleted from another tab.

like image 25
Mario Lamacchia Avatar answered Dec 09 '25 16:12

Mario Lamacchia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!