I've been experimenting with Pinia for state management in my Vue application, but I've encountered an issue where Pinia is being used before it's initialized in the main.js file.
Below is the code snippet from the routes file:
import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../stores/user'
const store = useUserStore()
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'login',
component: () => import('../views/LoginView.vue')
},
{
path: '/Dash',
name: 'dash',
component: () => import('../views/authed/DashView.vue')
},
{
path: '/Register',
name: 'register',
component: () => import('../views/RegisterView.vue')
}
]
})
export default router
This section manages the user data in a file named user.js:
import { ref, computed, watch } from 'vue'
import { defineStore } from 'pinia'
import axios from 'axios'
// Define user data store using Pinia
export const useUserStore = defineStore('user', () => {
const user = ref ({
name: "",
token: "",
auth: false,
})
// Additional methods for setting and checking authentication status
return {
user,
setAuth,
checkAuth,
}
},
{
persist: true
})
The following code segment is from the main.js file:
import { createApp, watch } from 'vue'
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
import App from './App.vue'
import router from './router'
import "bootstrap/dist/css/bootstrap.min.css";
import "bootstrap";
import axios from 'axios'
import './assets/main.css'
const pinia = createPinia()
// Initializing Pinia and creating the app instance
const app = createApp(App)
pinia.use(piniaPluginPersistedstate)
app.use(pinia)
app.use(router, axios)
app.mount('#app')
Unfortunately, an error has been occurring. The error message reads:
Uncaught Error: [🍍]: getActivePinia was called with no active Pinia. Did you forget to install pinia?
This occurs when attempting to authenticate users for specific routes in the router file.</p>
<pre><code>import {useUserStore} from '../stores/user'
store = useUserStore()
An attempt was made to modify the main.js file based on previous suggestions, however, the error persists despite changing the import location.
import { createApp, watch } from 'vue'
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
import App from './App.vue'
import "bootstrap/dist/css/bootstrap.min.css";
import "bootstrap";
import axios from 'axios'
import './assets/main.css'
const pinia = createPinia()
const app = createApp(App)
pinia.use(piniaPluginPersistedstate)
app.use(pinia)
import router from './router'
app.use(router, axios)
app.mount('#app')