Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve handling of auth store loading state #543

Merged
merged 1 commit into from
Feb 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions resources/src/auto-imports.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,7 @@ declare global {
// for vue template auto import
import { UnwrapRef } from 'vue'
declare module 'vue' {
interface GlobalComponents {}
interface ComponentCustomProperties {
readonly $$: UnwrapRef<typeof import('vue/macros')['$$']>
readonly $: UnwrapRef<typeof import('vue/macros')['$']>
Expand Down Expand Up @@ -638,6 +639,7 @@ declare module 'vue' {
}
}
declare module '@vue/runtime-core' {
interface GlobalComponents {}
interface ComponentCustomProperties {
readonly $$: UnwrapRef<typeof import('vue/macros')['$$']>
readonly $: UnwrapRef<typeof import('vue/macros')['$']>
Expand Down
4 changes: 2 additions & 2 deletions resources/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ installRouter(myApp);
// Global navigation guard
const authStore = useAuthStore();

Router.beforeEach((to, from) => {
Router.beforeEach(async (to, from) => {
// check if pages requires auth
if (authStore.loading) {
return;
await authStore.waitForLoading();
}

if (to.matched.some((record) => record.meta.requiresAuth)) {
Expand Down
13 changes: 13 additions & 0 deletions resources/src/stores/AuthStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,18 @@ export const useAuthStore = defineStore('AuthStore', () => {
}
}

/** Function that returns when loading is done */
async function waitForLoading() {
return new Promise((resolve) => {
const interval = setInterval(() => {
if (!loading.value) {
clearInterval(interval);
resolve(true);
}
}, 100);
});
}

/**
* Get authenticated user from backend
* @returns AuthenticatedUser | null (if not authenticated)
Expand Down Expand Up @@ -144,6 +156,7 @@ export const useAuthStore = defineStore('AuthStore', () => {
logout,
refreshUser,
loading,
waitForLoading,
idleTimerMin,
getAuthentications,
userAuthentications,
Expand Down
Loading