Can't access pinia in router.js file (or other util js files) #1155
-
I can access pinia if I define the route in main.js but I cannot access it if I call it in a separate router.js file. my main .js // main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import { loadAllPlugins } from './plugins'
...
const app = createApp(App)
loadAllPlugins(app).then(() => app.use(router).mount('#app')) My load all plugins file // plugins/index.js
export function loadAllPlugins(app) {
return new Promise((resolve) => {
// register all files in plugins directory
const files = require.context('.', true, /\.js$/)
files.keys().forEach((key) => {
if (typeof files(key).default === 'function') {
if (key !== './index.js') files(key).default(app)
}
})
resolve()
})
} // plugins/pinia.js
import { createPinia } from 'pinia'
const $fetch = ...
export default function loadPlugin(app) {
const pinia = createPinia()
// register fetch to pinia
pinia.use(({ store }) => {
store.$fetch = $fetch
})
app.use(pinia)
} as you can see, I waited for all the plugins to load before calling // store/index.js
import { defineStore } from 'pinia'
export const useStore = defineStore({
id: 'store',
state: () => ({
mainFilter: CONST.SPENDING,
})
...
}) // router.js
import { createWebHistory, createRouter } from 'vue-router'
import { useStore } from '../store'
const store = useStore()
const routes = [
{
path: '/',
name: 'Statistics',
component: () => import('@/pages/HomePage'),
meta: { filter: store.mainFilter }, // <=== call state here throw error
}]
const router = createRouter({
history: createWebHistory('/#/'),
routes,
})
export default router Here is what the error says Uncaught 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. This not only happen in router.js file but to any helper file I called |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
i am facing the same issue did you find something please |
Beta Was this translation helpful? Give feedback.
-
See https://pinia.vuejs.org/cookbook/migration-vuex.html#Usage-Outside-Components |
Beta Was this translation helpful? Give feedback.
See https://pinia.vuejs.org/cookbook/migration-vuex.html#Usage-Outside-Components