To address the issue of the user state not being updated quickly enough after a successful login, you can consider a few strategies to ensure that the authentication state is correctly set before the admin dashboard page is mounted. Here are some potential solutions:
-
Use a Promise or Async/Await for State Update: Ensure that the login process, including the state update, is completed before navigating to the admin dashboard. You can achieve this by using promises or async/await to handle the login process.
-
Route Guards: Implement route guards to check the authentication state before allowing access to the admin dashboard. This way, the navigation to the admin page will only occur if the user is authenticated.
-
Event Bus or Emit Events: Use an event bus or emit events to notify the admin dashboard component when the user state has been updated. This can help in delaying the execution of the
onMountedlogic until the user state is confirmed.
Here's an example of how you might implement a route guard in Vue Router to ensure the user is authenticated before accessing the admin dashboard:
// router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import { useUserStore } from '@flighter/stores';
import AdminDashboard from '@/views/AdminDashboard.vue';
import HomePage from '@/views/HomePage.vue';
const routes = [
{
path: '/admin',
component: AdminDashboard,
beforeEnter: (to, from, next) => {
const userStore = useUserStore();
if (userStore.authenticated) {
next();
} else {
next('/');
}
},
},
{
path: '/',
component: HomePage,
},
];
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;
-
Delay the
onMountedLogic: You can delay the execution of theonMountedlogic until the user state is confirmed. This can be done by using a watcher on theauthenticatedstate or by using a setTimeout as a temporary workaround.
import { watch } from 'vue';
import { useUserStore } from '@flighter/stores';
onMounted(() => {
const userStore = useUserStore();
watch(
() => userStore.authenticated,
(isAuthenticated) => {
if (!props.allowGuests && !isAuthenticated) {
console.log('Should redirect to guest page', userStore.user);
// router.push('/');
} else {
console.log('Should not redirect to guest page', userStore.user);
}
},
{ immediate: true }
);
});
By implementing one or a combination of these strategies, you should be able to ensure that the user state is correctly updated before the admin dashboard is accessed, preventing the unwanted redirection.