Search code examples
javascriptvue.jsnuxt.jspinianuxt-plugin

nuxt3 how to call pinia store in composeable


Since the nuxt 3.4.0 update the pinia store can no longer be used in composeables.

//example composable
import { useAuthStore } from '~/store/auth-store';
const authStore = useAuthStore();

export function doSomethingWithStore() {
  return authStore.checkAuthUser;
}

you will now receive the below error

getActivePinia was called with no active Pinia. Did you forget to install pinia? const pinia = createPinia() app.use(pinia) This will fail in production.

see stackblitz example https://stackblitz.com/edit/broken-pinia-store-in-composeables?file=composables%2FthisBreaks.js,nuxt.config.ts


Solution

  • It is because const authStore = useAuthStore(); declared outside any function like you did is called at some early point of application startup and definitely before Pinia instance is properly initialized inside Vue instance.

    Like this it will work:

    import { useAuthStore } from '~/store/auth-store';
    
    export function doSomethingWithStore() {
      const authStore = useAuthStore();
      return authStore.checkAuthUser;
    }
    

    Safe places to do Pinia calls (might not be a complete list):

    • from within <script setup>
    • inline in <template> section
    • inside defineNuxtMiddleware