[Vuejs]-Error with Vue.js 3, Pinia and global store

1👍

You forgot to create Pinia’s instance with the createPinia function.

So, your code should be like the following example:

import { createApp } from "vue"
import { createPinia } from 'pinia'
import App from "./App.vue"
import { router } from "./router"
import "./assets/main.css"

const app = createApp(App);
const pinia = createPinia();
app.use(pinia);
app.use(router);
app.mount("#app");

1👍

useAuthStore isn’t supposed to be called at the top of a module, this defies the purpose of having getter function for a store. When used outside a component, useAuthStore should be always called at the place where a store is used in order to prevent early store instantiation, i.e. inside api:

import {APISettings} from './config';
import {useAuthStore, useNotificationStore} from '@/stores';

export function api(method: string, url: string): Promise<any>;
export function api(method: string, url: string, data: any): Promise<any>;
export function api(method: string, url: string, data?: any): Promise<any> {
export function api(method: string, url: string, data?: any): Promise<any> {
  const authStore = useAuthStore();
  const notificationStore = useNotificationStore();
  ...

Also src/api/constants.ts seems to be a useless abstraction, this code belongs to store actions.

It’s possible that src/main.ts doesn’t look exactly like it’s shown, but in case it is, this means that Pinia isn’t correctly initialized and another answer is also applicable.

Leave a comment