I want to load one of three possible routes depending on a users role in my pinia store. The current problem I'm having is that the pinia store doesn't seem to be initalised before the router has been set getting the error
Uncaught Error: [🍍]: getActivePinia was called with no active
is there a way for me to address this issue?
For reference the routes are set like
const roleOneRoutes = [
{
path: '/home',
name: 'home',
component: () => import('@/pages/RoleOne/Home'),
},
...
]
const roleTwoRoutes = [
{
path: '/home',
name: 'home',
component: () => import('@/pages/RoleTwo/Home'),
},
...
]
Then in the index file I would ideally want something similar
const { user } = useAuthStore()
const mappedRoutes = user.role === 'roleOne' ? roleOneRoutes : roleTwoRoutes
export const router = createRouter({
history: createWebHistory(),
routes: mappedRoutes
})
Pinia store cannot be normally accessed at the top of a module, useAuthStore
is a function and not an object because this allows to prevent eager access. It should be called in the place where store data is actually needed. In this case this would result in race condition because user
is likely not set at this moment.
View component can be conditionally set like this:
{
path: '/home',
name: 'home',
component: () => useAuthStore().user.role === 'roleOne'
? import('@/pages/RoleOne/Home')
: import('@/pages/RoleTwo/Home')
},