From 5fcc2d80a7dccd1682e7f75f6aee8027fb15e167 Mon Sep 17 00:00:00 2001 From: LittleSheep Date: Sat, 4 Oct 2025 18:56:08 +0800 Subject: [PATCH] :bug: Fix user loading exit early when there is another async doing that to fix the auth middleware --- app/stores/user.ts | 54 +++++++++++++++++++++++++--------------------- 1 file changed, 30 insertions(+), 24 deletions(-) diff --git a/app/stores/user.ts b/app/stores/user.ts index 235d465..96e2ddc 100644 --- a/app/stores/user.ts +++ b/app/stores/user.ts @@ -9,43 +9,49 @@ export const useUserStore = defineStore("user", () => { const user = ref(null) const isLoading = ref(false) const error = ref(null) + const currentFetchPromise = ref | null>(null) // Getters const isAuthenticated = computed(() => !!user.value) // Actions - async function fetchUser(reload = true) { - if (isLoading.value) { - console.log("[UserStore] Fetch already in progress. Skipping.") - return + async function fetchUser(reload = true): Promise { + if (currentFetchPromise.value) { + console.log("[UserStore] Fetch already in progress. Waiting for existing fetch.") + return currentFetchPromise.value } if (!reload && user.value) { console.log( `[UserStore] User store was loaded with account @${user.value.name} and no reload. Skipping.` ) - return + return Promise.resolve() } - isLoading.value = true - error.value = null - const api = useSolarNetwork() - try { - const response = await api("/id/accounts/me") - console.log("[UserStore] Fetched user data: ", response) - user.value = response - console.log(`[UserStore] Logged in as @${user.value.name}`) - } catch (e: unknown) { - if (e instanceof FetchError && e.statusCode == 401) { - error.value = "Unauthorized" - user.value = null - } else { - error.value = e instanceof Error ? e.message : "An error occurred" - user.value = null // Clear user data on error - console.error("Failed to fetch user... ", e) + const fetchPromise = (async () => { + isLoading.value = true + error.value = null + const api = useSolarNetwork() + try { + const response = await api("/id/accounts/me") + user.value = response + console.log(`[UserStore] Logged in as @${user.value.name}`) + } catch (e: unknown) { + if (e instanceof FetchError && e.statusCode == 401) { + error.value = "Unauthorized" + user.value = null + } else { + error.value = e instanceof Error ? e.message : "An error occurred" + user.value = null // Clear user data on error + console.error("Failed to fetch user... ", e) + } + } finally { + isLoading.value = false + currentFetchPromise.value = null } - } finally { - isLoading.value = false - } + })() + + currentFetchPromise.value = fetchPromise + return fetchPromise } function logout() {