thiebo
thiebo

Reputation: 1435

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

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
]

Upvotes: 9

Views: 6732

Answers (2)

Lee Goddard
Lee Goddard

Reputation: 11173

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

Upvotes: 7

salih bulmaz
salih bulmaz

Reputation: 5

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

Upvotes: -3

Related Questions