search

Home  >  Q&A  >  body text

Learn how to use Composeable to call Pinia store in Nuxt 3

<p>Since nuxt 3.4.0 update, pinia store cannot be used in composeables. </p> <pre class="brush:php;toolbar:false;">//Example composeable import { useAuthStore } from '~/store/auth-store'; const authStore = useAuthStore(); export function doSomethingWithStore() { return authStore.checkAuthUser; }</pre> <p>You will receive the following error</p> <pre class="brush:php;toolbar:false;">getActivePinia was called with no active Pinia. Did you forget to install pinia? const pinia = createPinia() app.use(pinia) This will fail in production. </pre> <p>View stackblitz example https://stackblitz.com/edit/broken-pinia-store-in-composeables?file=composables/thisBreaks.js,nuxt.config.ts</p>
P粉418351692P粉418351692464 days ago728

reply all(2)I'll reply

  • P粉186897465

    P粉1868974652023-08-27 08:07:09

    You installed the @pinia/nuxt module incorrectly in nuxt.config.ts. In Nuxt 3, the buildModules attribute no longer exists and you need to use modules instead (you can tell by the TypeScript error):

    // nuxt.config.ts
    export default defineNuxtConfig({
      // replace buildModules by modules
      modules: ['@pinia/nuxt'],
    });
    

    Second point, you also need to call useAuthStore inside the combiner function, otherwise it will try to load the store before pinia actually loads. It is called when the file is imported, not when the combiner function is used.

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

    Please refer to this working stackblitz

    reply
    0
  • P粉378264633

    P粉3782646332023-08-27 00:19:28

    This is because declaring const authStore = useAuthStore(); outside of any function like you did will be called at some early stage of application startup, and correctly within the Vue instance Before initializing the Pinia instance.

    This will work:

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

    Places where it is safe to make Pinia calls (may not be a complete list):

    • Inside<script setup>Internal
    • Inline in <template> section
    • In defineNuxtMiddlewareInternal

    reply
    0
  • Cancelreply