'Persisted Vuex and storage timing issue in NuxtJS

So I have a timing issue I believe with Vuex and https://github.com/championswimmer/vuex-persist package.

What I am doing:

  • I wrote a plugin to authenticate with auth code grant with pixie.
  • This plugin adds my own and custom vuex auth module.
  • I am storing the entire Vuex store along with tokens and things in encrypted local storage.
  • I am passing the store to my service.
  • When I try to access my store immediately, a specific field in the state, the data is not there but it is there if I just dump the store object.

This is my code where the problem occurs.

import authModule from './store/modules/auth/auth.js'
import { AuthService } from "~/plugins/auth/services/AuthService";

export default({app, store, $axios}, inject) => {
  store.registerModule('auth', authModule, { preserveState: !!store.hasModule('auth') })
  inject('auth', new AuthService(store))
   
  // this will be incorrect and token will be null ===> this.$store.state.auth.token !== null
  console.log('app.$auth.hasAccessToken', app.$auth.hasAccessToken)

  // this will be OK and token will be there when I expand the object in the console
  console.log(app.store)
}

So what I think happens is it takes time to load data from encrypted storage and when I want to access it immediately it is not there.

If I just dump out the object, it gets updated I guess before it's printed to the console and I see what I need to see.

I was wondering if anyone knows how I could extend default vuex mutations to add events when mutation takes place or when the store is updated. I could then register event listener so I would only proceed when everything is loaded if that makes sense.

So essentially what I want is a way to tell that my store is fully loaded on go on only when everything is ready.

Does that makes sense? Maybe there is a better way?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source