Search code examples
vuexnuxt.jsvue-ssr

Nuxt.js with vuex-persist - persisted state not available in asyncData upon page refresh


Upon first page refresh, the asyncData function is not able to fetch the persisted state. When I follow another NuxtLink, and go back to this page, while the state is not mutated in the meantime, the data is there. This means the persisted state is not available on the server side at first load/refresh. LocalStorage is where I choose to persist the relevant state items.

A pages component that uses asyncData:

  asyncData({ app, params, store }) {
  //its not available upon first refresh, but is after following a random nuxtlink and going back
    const cartProducts = store.getters.getCartProducts 
},

store/index.js is straightforward. Unfortunately, the state is completely empty in asyncData upon first page refresh.

  getCartProducts(state) {
    return state.cart.products
  },

vuex-persist.js imported properly with mode 'client' as recommended in the Github Readme

import VuexPersistence from 'vuex-persist'
/** https://github.com/championswimmer/vuex-persist#tips-for-nuxt */

export default ({ store }) => {
  window.onNuxtReady(() => {
    new VuexPersistence({
      key: 'cartStorage'
      /* your options */
    }).plugin(store)
  })
}

How can I make sure the relevant store terms from local storage are persisted before asyncData is called?


Solution

  • You can't do this. Its impossible. There is no localstorage on server. And asyncData executed on server on first load/refresh. So there is no way to get data from in asyncData from localstorage on server even theoretically.