4

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?

ViBoNaCci
  • 390
  • 3
  • 15

1 Answers1

7

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.

therealak12
  • 1,178
  • 2
  • 12
  • 26
Aldarund
  • 17,312
  • 5
  • 73
  • 104
  • So using state is not the right decision for a shopping cart type implementation then. Server session should work fine. Concept of SSR still confuses me, thanks for the answer once again. – ViBoNaCci Jul 14 '19 at 21:19
  • @ViBoNaCci ye it might be confusing at first. And yes, its much better to have cart contents on server tied to account if u can. For client persistence only cookies could be used. E.g. some custom module for vuex that use universal-cookie as a storage option or nuxt-universal storage package – Aldarund Jul 14 '19 at 21:35
  • check out [nuxtServerInit](https://nuxtjs.org/guide/vuex-store#the-nuxtserverinit-action) for how to populate server data into the store on server load. You're also able to access req/res from [asyncData](https://nuxtjs.org/guide/async-data/#use-code-req-code-code-res-code-objects) – HMilbradt Jul 15 '19 at 18:41