Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 386
ViBoNaCci Avatar asked Oct 28 '25 03:10

ViBoNaCci


1 Answers

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.

like image 144
Aldarund Avatar answered Oct 31 '25 11:10

Aldarund



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!