So, I am having issue with my Pinia store and router guard. Issue is following:
When i go trough ‘logout’ function that basically do following, everything comes in place.
logout function in auth.js pinia store
`async logout() {
this.user = null;
this.session = null;
this.token = null;
this.isEmailVerified = false;
// Clear local storage
localStorage.removeItem('user');
localStorage.removeItem('session');
localStorage.removeItem('token');
localStorage.removeItem('isEmailVerified');
const showStore = useShowStore();
showStore.closeMenu()
},`
But when I mannualy remove my session from chrome dev tools(remove session from local storage, token, user, and isEmailVerified) Pinia obviously does not update the state. But the issue is following: I try to get the state from pinia in router guard, and it still keeps previous state, it does not go and actually look in local storage and gets me updated data for session, token, etc
Here is my auth.js pinia store:
`import { defineStore } from 'pinia';
import { useShowStore } from "@/store/showStore";
export const useAuthStore = defineStore({
id: 'auth',
state: () => ({
user: JSON.parse(localStorage.getItem('user')) || null,
session: JSON.parse(localStorage.getItem('session')) || null,
token: localStorage.getItem('token') || null,
isEmailVerified: JSON.parse(localStorage.getItem('isEmailVerified')) || false,
}),
getters: {
isAuthenticated: () => !!localStorage.getItem('token') || null,
},
actions: {
async login(email, password) {
//...`
And here is router guard
`router.beforeEach((to, from, next) => {
const authStore = useAuthStore();
//here it prints session after removing manually
console.log('Is Authenticated:', authStore.isAuthenticated);
if (to.meta.requiresAuth && !authStore.isAuthenticated) {
next('/SignIn'); // Redirect to SignIn if not authenticated
} else if (to.meta.approachOnlyLoggedOut && authStore.isAuthenticated && authStore.isEmailVerified) {
next('/'); // Redirect to dashboard if authenticated and email verified
} else if (authStore.isAuthenticated && !authStore.isEmailVerified && to.path !== '/EmailVerification') {
if (to.path == "/VerifyEmail") {
next()
} else {
next('/EmailVerification'); // Redirect to EmailVerification if email is not verified
}
} else {
next();
}
});`
How can i get fresh state each time? I don’t want to update state trough action in router, since I will use this ‘isAuthenticated’ on many places in the app, so I don’t want to invoke another action before i get the state, I want this logic centralized.
I have tried many things, but it still keeps state as previous value. Can someone help? Thanks
Milan Milosevic is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.