Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

created hook for vuex / nuxtClientInit?

I was wondering whats the best way to do something like nuxtClientInit. I'm trying to load the Auth State as early as possible on the client and save it in my vuex store but not on the server side. It would be great if vuex had something like the created hook for components but that doesn't exist to my knowledge.

How could I achieve this behavior? One way could be calling an action from a layout but is that the best way?

like image 534
Jonas Avatar asked Apr 01 '19 20:04

Jonas


1 Answers

I understand the nuxt team are working on a nuxtClientInit feature but before they release that you could just make your own. To understand the workflow that nuxt undertakes when there is a request you can look at the lifecycle here. This shows that nuxtServerInit is called first then middleware. During this middleware call nuxt.config.js is served and this contains your custom configuration. Part of this is 'plugins' which as the docs say,

This option lets you define JavaScript plugins that should be run before instantiating the root Vue.js application.

So if you write a plugin to call a store action you can then get and set your local storage from there. So, start with a nuxt-client-init plugin:

//nuxt-client-init.client.js
export default async context => {
  await context.store.dispatch('nuxtClientInit', context)
}

then add the plugin to nuxt.config.js:

//nuxt.config.js
  plugins: [
    '~/plugins/nuxt-client-init.client.js'
  ],

If you notice the naming convention here, the .client.js part of the plugin tells nuxt this is a client only plugin and is shorthand for '{ src: '~/plugins/nuxt-client-init.js', mode: 'client' }' which since nuxt 2.4 is the way to define the old '{ src: '~/plugins/nuxt-client-init.js', ssr: false }'. Anyway, you now have a call to your store so you can have an action to call from local storage and set a state item.

//store/index.js
export const actions = {
  nuxtClientInit({ commit }, { req }) {
    const autho = localStorage.getItem('auth._token.local') //or whatever yours is called
    commit('SET_AUTHO', autho)
    console.log('From nuxtClientInit - '+autho)
  }
}

You probably need to restart your app for that to all take effect but you are then getting and using your Auth State without any of that pesky nuxtServerInit business.

like image 129
Andrew1325 Avatar answered Sep 19 '22 18:09

Andrew1325