'Check if vuex-persist has restored data in Nuxt project

I have added Vuex-Persist and Vuex-ORM to my Nuxt project. When the application starts for the first time I want to add some boilerplate data.

In my default.vue layout I have added a created function to add this dummy data.

<script>
import Project from '../models/Project';

export default {
  created () {
    // I'm Using Vuex-Orm to check if there are any projects stored
    if (Project.query().count() === 0) {
      Project.insert({ data: [{ title: 'My first project' }] })
    }
  }
}
</script>

When the application is reloaded and opens for the second time, I would expect that Project.query().count() returns 1. But it will always return 0 because vuex-persist isn't done restoring the local data yet.

According to the docs this would be the solution

import { store } from '@/store' // ...or wherever your `vuex` store is defined

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

store.defined is undefined and same goes for this.$store. That comment highlights my exact question "Where is my vuex store defined?"



Solution 1:[1]

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' }] })
    }
  });
}

Solution 2:[2]

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
        }
    }

}

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Tomas
Solution 2 4ern