vue.jsasynchronousnuxt.jsvuex

NuxtJS store returning local storage values as undefined


I have a nuxt application. One of the components in it's mounted lifecycle hook is requesting a value from the state store, this value is retrieved from local storage. The values exist in local storage however the store returns it as undefined. If I render the values in the ui with {{value}} they show. So it appears that in the moment that the code runs, the value is undefined.

index.js (store):

export const state = () => ({
  token: process.browser ? localStorage.getItem("token") : undefined,
  user_id: process.browser ? localStorage.getItem("user_id") : undefined,
...

Component.vue

mounted hook: I'm using UserSerivce.getFromStorage to get the value directly from localStorage as otherwise this code block won't run. It's a temporary thing to illustrate the problem.

async mounted() {
  // check again with new code. 
  if (UserService.getFromStorage("token")) {
    console.log("user service found a token but what about store?")
    console.log(this.$store.state.token, this.$store.state.user_id);

    const values = await ["token", "user_id"].map(key => {return UserService.getFromStorage(key)});
    console.log({values});
    SocketService.trackSession(this, socket, "connect")
  }
}

BeforeMount hook:

isLoggedIn just checks that the "token" property is set in the store state. return !!this.$store.state.token

beforeMount () {
  if (this.isLoggedIn) {
    // This runs sometimes??? 80% of the time.
    console.log("IS THIS CLAUSE RUNNING?");
  }
}

video explanation: https://www.loom.com/share/541ed2f77d3f46eeb5c2436f761442f4


Solution

  • OP's app is quite big from what it looks, so finding the exact reason is kinda difficult.
    Meanwhile, setting ssr: false fixed the errors.

    It raised more, but they should probably be asked into another question nonetheless.