[Vuejs]-Check if vuex-persist has restored data in Nuxt project

0👍

I followed the instructions from vuex-persist for Nuxt and made a plugin file, like this:

// ~/plugins/vuex-persist.js
import VuexPersistence from 'vuex-persist'

export default ({ store }) => {
  window.onNuxtReady(() => {
    new VuexPersistence({
    /* your options */
    }).plugin(store);
  });
}

window.onNuxtReady caused the plugin to be loaded after all other code had run. So I didn’t matter if I made a router-guard.js plugin or tried it in the layout/default.vue file.

I ended up with the quick fix:

// ~/plugins/vuex-persist.js
import VuexPersistence from 'vuex-persist'

export default ({ store }) => {
 window.onNuxtReady(() => {
    new VuexPersistence().plugin(store);

    if (Project.query().count() === 0) {
      Project.insert({ data: [{ title: 'My first project' }] })
    }
  });
}

0👍

i think you have to put the whole thing in a route guard.

create a route-guard.js plugin like this. but I haven’t tested the whole thing, hope it helps you further.

export default function ({app}) {

    const waitForStorageToBeReady = async (to, from, next) => {
        await store.restored
        next()
    }

    app.router.beforeEach(waitForStorageToBeReady);
}

Another option is to put a getter in computed and watch it:

export default {

    computed: {
        persistState() {
            return this.store.getter['get_persis_state'];
        }
    },

    watch: {
        persistState(newVal) {
            // check new val
        }
    }

}

Leave a comment