How to Implement nuxtServerInit Action to load data from server-side on the initial load in Pinia (Nuxt3)

Viewed 481

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.

1 Answers

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
      }
    }
  }
}
Related