5

My Code:

export const useMenuStore = defineStore("menuStore", {
  state: () => ({
    menus: [],
  }),
  actions: {
    async nuxtServerInit() {
     
       const { body } = await fetch("https://jsonplaceholder.typicode.com/posts/1").then((response) => response.json());
       console.log(body);
       this.menus = body;
       resolve();
    },
   
  },
});

NuxtServerInit is not working on initial page render on nuxt js vuex module mode.Anyone know this error please help me.

kissu
  • 40,416
  • 14
  • 65
  • 133
Minh Yến
  • 97
  • 4

2 Answers2

2

In Nuxt2, the Nuxt will run the code in nuxtServerInit() of store/index.js on the server-side to boot the app.

However, in Nuxt3, there is no specific place to write the boot code, you can write the boot code anywhere instead of in nuxtServerInit() of store/index.js.

It might be helpful, especially when you need to send a request before boosting the app.


your pinia file may define like following:

store/menu.js

import { defineStore } from 'pinia';

export const useMenuStore = defineStore('menuStore', {
    state: () => ({
        _menus: [],
    }),
    getters: {
       menus() {
          return this._menus;
       }
    },
    actions: {
        async boot() {
            const { data } = await useFetch('https://jsonplaceholder.typicode.com/posts/1');
            this._menus = data;
        }
    }
});

Then, create a plugin which named as *.server.[ts|js], for example init.server.js

(.sever.js tail will let the file only run in server side)

plugins/init.server.js

import { defineNuxtPlugin } from '#app';
import { useMenuStore } from '~/store/menu.js';

export default defineNuxtPlugin(async (nuxtApp) => {
    const menu = useMenuStore(nuxtApp.$pinia);
    await menu.boot();
});

nuxt.config.js

modules: [
    '@pinia/nuxt',
],

There is an entire example of SSR Nuxt3 with authorization that may help

DengSihan
  • 2,119
  • 1
  • 13
  • 40
1

NuxtServerInit is not implemented in Pinia, but exists a workaround.

Using Pinia alongside Vuex

// nuxt.config.js
export default {
  buildModules: [
    '@nuxtjs/composition-api/module',
    ['@pinia/nuxt', { disableVuex: false }],
  ],
  // ... other options
}

then Include an index.js file inside /stores with a nuxtServerInit action which will be called from the server-side on the initial load.

// store/index.js
import { useSessionStore } from '~/stores/session'

export const actions = {
  async nuxtServerInit ({ dispatch }, { req, redirect, $pinia }) {
    if (!req.url.includes('/auth/')) {
      const store = useSessionStore($pinia)

      try {
        await store.me() // load user information from the server-side before rendering on client-side
      } catch (e) {
        redirect('/auth/login') // redirects to login if user is not logged in
      }
    }
  }
}
regex
  • 263
  • 4
  • 11