Learn how to use Composeable to call Pinia store in Nuxt 3
P粉418351692
2023-08-26 09:34:11
<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>
You installed the @pinia/nuxt module incorrectly in
nuxt.config.ts
. In Nuxt 3, thebuildModules
attribute no longer exists and you need to usemodules
instead (you can tell by the TypeScript error):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.Please refer to this working stackblitz
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:
Places where it is safe to make Pinia calls (may not be a complete list):
<script setup>
Internal<template>
sectiondefineNuxtMiddleware
Internal