how to use pinia store in a vue router navigation guard?
Asked Answered
D

2

9

I'm using Vuejs 3, vuerouter 4 and pinia and trying to put a navigation guard in some routes, as per the example in the documentation (if a user is not authenticated and is not on the login page, send the user to login page to get authenticated). This is explained also in pinia documentation on use of pinia outside of components. But I can't get my head around it.

The store I use is currently simple (return false or true on isAuthenticated):

//authStore.js
import { defineStore } from "pinia";

export const useAuthStore = defineStore( 'AuthStore', {

  state: () => {
    return {
      isAuthenticated: false
    }
  }

})

I want to use this isAuthenticated in a beforeEnter in routes/index.js

In main.js:


import { useAuthStore } from '@/stores/authStore'
import { createApp } from 'vue'
import App from './App.vue'
import router from '@/router'
import { createPinia } from 'pinia'

const app = createApp(App)
app.use(createPinia()).use(router)
app.mount('#app')

// I'm not using authStore in this file, so this raises an error:
const authStore = useAuthStore()

And in router/index.js:

import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  // path for login page,
  {
    path: '/adm/home',
    name: 'AdmView',
    component: () => import('@/views/adm/AdmView.vue'),
    beforeEnter: (to) => {
      // error: authStore is not defined
      const isAuthenticated = authStore
      if ( !isAuthenticated && to.name !== 'login-adm' ) {
        return { name: 'login-adm' }
      }
    }
  },
  // other paths
]
Defrayal answered 16/5, 2022 at 4:52 Comment(0)
C
7

Your authStore.js exports useAuthStore as expected, but you do not call it as required.

authStore is not defined because authStore is the filename of your auth store -- instead you should be executing the function useAuthStore exported from that file:

const authStore = useAuthStore();
console.log('Is authenticated?', authStore.isAuthenticated);
Cyanamide answered 12/7, 2022 at 13:28 Comment(0)
A
-3

I don't know if it is the main issue but u forgot to use a destructor on userStore doing

const isAuthenticated = authStore

It supposed to be

const { isAuthenticated } = toRefs(authStore);

toRefs to preserve reactivity after passing. It can be imported as

import { toRefs } from 'vue';
Arzola answered 16/5, 2022 at 6:57 Comment(2)
You're right about that, but: to maintain reactivity when destricturing in pinia, the function is storeToRefs, not toRefs which is used when destructuring reactive : pinia.vuejs.org/api/modules/pinia.html#storetorefs This is not the problem though.Defrayal
U have to define userstore after importing it, thats why it is undefinedArzola

© 2022 - 2024 — McMap. All rights reserved.