Search code examples
javascriptvue.jsvuejs3vue-routerpinia

Pinia not initilizing in router for vue js


I have been trying to use Pinia for state management in my vue application. I've been running into the issue where pinia is being used before its initialised in the main.js folder.

This is 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'),
      // beforeEnter: (to, from) => {
      // }
    },
    {
      path: '/Register',
      name: 'register',
      component: () => import('../views/RegisterView.vue')
    }
  ]
})



export default router

This is the place where is store the data. user.js

import { ref, computed, watch } from 'vue'
import { defineStore } from 'pinia'
import axios from 'axios'



export const useUserStore = defineStore('user', () => {
    const user = ref ({
        name: "",
        token: "",
        auth: false,
        
    })


    // if (localStorage.getItem('user')) {
    //     user.value = JSON.parse(localStorage.getItem('user'))
    // }
    // watch(
    //     user,
    //         (userVal) => {
    //             localStorage.setItem('User', JSON.stringify(userVal))
    //         },
    //         { deep: true}
    // )

    const setAuth = (newToken, successAuth, authedName) => {
        user.value.token = newToken
        user.value.auth = successAuth
        user.value.name = authedName
    }

    const checkAuth = () => {
        try {
            const response =  axios.post('api/get-user', {}, {
                headers: {
                    Authorization: `Bearer ${user.value.token}`
                }
            })
            .then(({ data: userData }) => {
                console.log('USER IS AUTHED')
            })
        } catch (err) {
            console.log(err)
        }
    }
    return {
        user,
        setAuth,
        checkAuth,
    }
},
{
    persist: true
})


This is 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()

// if (localStorage.getItem('user')) {
//     pinia.user.value = JSON.parse(localstorage.getItem('user'))

// }

// watch(
//     pinia.state,
//     (state) => {
//         localStorage.setItem('state', JSON.stringify(state))
//     },
//     { deep: true }
// )


const app = createApp(App)
pinia.use(piniaPluginPersistedstate)
app.use(pinia)
app.use(router, axios)

app.mount('#app')

This is my error...

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.
    at useStore (pinia.js?v=3c6f7703:1256:13)
    at index.js?t=1658100067018:5:9

The error happens when I add to the router file, I need to use it here so I can authenticate users to use certain routes.

import {useUserStore} from '../stores/user'


store = useUserStore()

This is the edit I've made to the main.js file from the first answer, however moving the place I import the file hasn't made a difference still getting the same error.

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')


Solution

  • in your main.js file when you import router from './router' this line will be excute const store = useUserStore() at this time Pinia is not define yet.