robinvdvleuten / vuex-persistedstate

💾 Persist and rehydrate your Vuex state between page reloads.
https://npm.im/vuex-persistedstate
MIT License
5.76k stars 375 forks source link

Newbe Question - Restore data from localStore to Vuex on page reload in Nuxt.js #438

Closed vishytk closed 2 years ago

vishytk commented 2 years ago

My Setup details:

the plugin code copied from the discussions here.

plugins/persistedstate.js

import createPersistedState from 'vuex-persistedstate'

export default ({ store, isHMR }) => {
  if (isHMR) return
  if (process.browser) {
    createPersistedState({
      key: applocal,
      paths: ['index', 'validation'],
    })(store)
  }
}

I can see the data stored in the localStore with the key name 'applocal'

I am new to programming and nuxt, so do not know how to write back the data from localstore to vuex on page reload. Currently, the page is going blank with vuex being empty.

vishytk commented 2 years ago

I have tried the following but has not worked for me.

added following function in store/index.js and tried calling the function from inside a page (pages/index.vue) But I get "localStore is not defined" error.

store/index.js

export const mutations = {
    initialiseStore(state) {
      // Check if the ID exists
      if (localStorage.getItem('ropapp')) {
        // Replace the state object with the stored item
        this.replaceState(
          Object.assign(state, JSON.parse(localStorage.getItem('ropapp')))
        )
      }
    },
}

pages/index.vue

beforeCreate() {
  console.log('Home: beforeCreate')
  console.log('Store: ', this.$store)
  this.$store.commit('initialiseStore')
}
vishytk commented 2 years ago

changed my code to:

plugins/persistedstate.js

import createPersistedState from 'vuex-persistedstate'

export default ({ store }) => {
  createPersistedState({
    key: 'applocal',
    storage: window.localStorage,
    overwrite: true,
  })(store)
}

removed store.index.js initialiseStore() mutation

Now, I am able to see data restored in Vuex when page is reloaded. But I am unable to access it from my pages.