0👍
for checking if a user is logged in and therefore gets access to routes with requiresAuth
i would handle with a login state. i’ll write you here an example how the function onAuthStateChange
could look like.
onAuthStateChanged(auth, (newUser) => {
user.value = newUser
if (newUser) {
user.value = newUser
// handle the login state here
this.isLoggedIn = true
// dont use router inside pinia
router.push({ name: 'content' })
} else {
router.push({ name: 'login' })
}
})
your function now has a state isloggedIn
, but of course you have to define it as a state first.
with this state you can check if the user has a logged in session or not and display your content accordingly.
your router push has actually lost nothing in this function. try it like this:
<div v-if="authStore.isLoggedIn" >
<router-view />
</div>
<div v-else>
<router-view name="auth" />
</div>
for this you have to define another named route for your requiredAuth
.
Now you just have it exactly like this:
If the user is logged in I use the default router-view, if not then the name="auth" router-view.
an example of a routeGuard that works in this case:
router.beforeEach((to, from, next) => {
const authStore = useAuthStore()
if (authStore.isLoggedIn && to.path === '/') {
next('/content')
return
}
if (!authStore.isLoggedIn && to.path !== '/login') {
next('/')
return
} else {
next()
return
}
})
this architectural approach is cleaner.
i hope this might solve your problem. if not let’s move on.