Search code examples
statevuexnuxt.js

Populate NUXTJS Store state content on startup?


I want my Nuxtjs store state (ssr: false, so no nuxtServerInit) with data when a user starts the application.

The goal is to make a date calculation on startup and store the answer on nuxtjs store, so when I need this information I do not need to recalculate again everytime (this information will be used on many pages).

Can this be done?


Solution

  • You can write a small plugin which will run on startup and can call a store action for you, similar to nuxtServerInit.

    // ~/plugins/nuxtClientInit.js
    
    export default async function (context) {
      await context.store.dispatch('nuxtClientInit', context)
    }
    

    Then simply add it to your nuxt.config.js.

    ...
    
    plugins: [
      { src: '~/plugins/nuxtClientInit.js', mode: 'client' }
    ],
    
    ...
    

    Now the nuxtClientInit store action will be called at startup, you can even access the context object.

    
    actions: {
      nuxtClientInit ({ commit }, context) {
        // commit(...)
      }
    }