From 6fadd63336c604afcf70bc4438219420ce374906 Mon Sep 17 00:00:00 2001 From: Mplan Date: Sun, 24 May 2026 16:25:26 +0800 Subject: [PATCH] fix: resolve auth initialization race and username flicker on login Always initialize auth before mounting the app so loading state completes and onAuthStateChange is registered on every route. Gate header auth UI on !loading to avoid flicker during email confirm and password reset flows. Load profile before setting user ref so displayUsername shows the correct name immediately instead of flashing the email. --- src/components/layout/AppHeader.vue | 70 +++++++++++++++-------------- src/main.ts | 9 +--- src/stores/auth.ts | 26 +++++++---- 3 files changed, 55 insertions(+), 50 deletions(-) diff --git a/src/components/layout/AppHeader.vue b/src/components/layout/AppHeader.vue index 414e90b..4375cf4 100644 --- a/src/components/layout/AppHeader.vue +++ b/src/components/layout/AppHeader.vue @@ -179,20 +179,21 @@ async function handleLogout() { - - + - 上传 - - + + 上传 + + - @@ -338,7 +340,7 @@ async function handleLogout() { 图鉴 { app.use(router) app.mount('#app') -} else { - authStore.initialize().then(() => { - app.use(router) - app.mount('#app') - }) -} +}) diff --git a/src/stores/auth.ts b/src/stores/auth.ts index 5bd1902..cc0fcab 100644 --- a/src/stores/auth.ts +++ b/src/stores/auth.ts @@ -12,12 +12,13 @@ export const useAuthStore = defineStore('auth', () => { const isLoggedIn = computed(() => !!user.value) const isAdmin = computed(() => profile.value?.role === 'admin') - async function fetchProfile() { - if (!user.value) return + async function fetchProfile(userId?: string) { + const id = userId ?? user.value?.id + if (!id) return const { data } = await supabase .from('profiles') .select('*') - .eq('id', user.value.id) + .eq('id', id) .single() if (data) { profile.value = data as Profile @@ -53,8 +54,8 @@ export const useAuthStore = defineStore('auth', () => { } throw error } + await fetchProfile(data.user.id) user.value = data.user - await fetchProfile() } async function register(email: string, password: string, username: string) { @@ -122,14 +123,21 @@ export const useAuthStore = defineStore('auth', () => { async function initialize() { const { data: { session } } = await supabase.auth.getSession() - user.value = session?.user ?? null - if (user.value) await fetchProfile() + const initialUser = session?.user ?? null + if (initialUser) await fetchProfile(initialUser.id) + user.value = initialUser loading.value = false supabase.auth.onAuthStateChange((_event, session) => { - user.value = session?.user ?? null - if (user.value) fetchProfile() - else profile.value = null + const nextUser = session?.user ?? null + if (nextUser) { + fetchProfile(nextUser.id).then(() => { + user.value = nextUser + }) + } else { + user.value = null + profile.value = null + } }) }