Nuxt 3: $pinia instance does not exist on nuxtApp when using defineNuxtPlugin(nuxtApp)
Asked Answered
G

1

6
Nuxt: 3.6.2
Pinia: 2.1.4
@pinia/nuxt: 0.4.11

While defining a Nuxt 3 plugin for Pinia I need to access the $pinia instance that exists on nuxtApp.

The defineNuxtPlugin() function passes on argument, the nuxtApp. https://nuxt.com/docs/guide/directory-structure/plugins#creating-plugins

When I destructure $piniafrom that argument (shown in pinia docs here) I receive the following type error:$pinia is of type unknown

But when I call useNuxtApp() to get $pinia within the defineNuxtPlugin() function, I have access to it. $pinia is available via useNuxtApp()

Any idea on why I the pinia example is not working for me?

So far I have followed the Nuxt 3 / Pinia installation guide as described as described here: https://pinia.vuejs.org/ssr/nuxt.html#installation

Gargoyle answered 11/7, 2023 at 22:25 Comment(0)
S
3

I use below code, to sum up is cast to Pinia type.

import { useMainStore } from '@/store';
import { Pinia } from 'pinia'; 

export default defineNuxtPlugin(({ $pinia }) => {
    const _pinia = $pinia as Pinia;

    if (!_pinia) return;

   return {
        provide: {
            store: useMainStore(_pinia),
        },
    };
});
Stephanus answered 17/10, 2023 at 5:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.