1

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

2 Answers2

3

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
Ellrohir
  • 1,017
  • 1
  • 14
  • 32
1

You wrongly installed the @pinia/nuxt module in nuxt.config.ts. The buildModules property no longer exists in Nuxt 3, you have to use modules instead. (And you can tell by the Typescript error you get):

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

Second point, you also need to call the useAuthStore from within the composable function, otherwise it's trying to load the store before pinia actually loaded. It's gonna get called when the file is imported, not when the composable is used.

import { useAuthStore } from '~/store/auth-store';

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

See a working stackblitz

Kapcash
  • 6,377
  • 2
  • 18
  • 40
  • yea sorry forgot to update it, though that issue is besides the point. you get the error regardless of how you import modules. i updated stackblitz to show you – Jean-Pierre Engelbrecht Apr 21 '23 at 16:01
  • I tested on stackblitz and got it working, but turns out it's a mix solution between mine and @Ellrohir ;-) I updated my answer with a working example. – Kapcash Apr 21 '23 at 21:15