How to get access beforeCreate() global app in Nuxt?

Viewed 374

I want to get access beforeCreate() app cycle method in Nuxt and load data from localStorage to Vuex store, how can I do that?

1 Answers

You could use Nuxt middleware to achieve a beforeCreate() effect.

// /nuxtproject/middleware/store_check.js
export default function ({ store }) {
  store.dispatch('stateModule/stateAction')
}

// /nuxtproject/pages/index.vue
export default {
  components: {
    Header
  },
  middleware: 'store_check',
}

As for loading from localStorage, you can use it with the middleware solution above provided Nuxt is running in SPA mode - because localStorage isn't natively available on Nuxt Universa/SSR mode.

Had this same problem after spending some hours and this other stackoverflow answer explains why (with alternatives)

https://stackoverflow.com/a/57512785/842834

Related