🐛 Fix user loading exit early when there is another async doing that to fix the auth middleware

This commit is contained in:
2025-10-04 18:56:08 +08:00
parent 9960eb4f4c
commit 5fcc2d80a7

View File

@@ -9,43 +9,49 @@ export const useUserStore = defineStore("user", () => {
const user = ref<SnAccount | null>(null) const user = ref<SnAccount | null>(null)
const isLoading = ref(false) const isLoading = ref(false)
const error = ref<string | null>(null) const error = ref<string | null>(null)
const currentFetchPromise = ref<Promise<void> | null>(null)
// Getters // Getters
const isAuthenticated = computed(() => !!user.value) const isAuthenticated = computed(() => !!user.value)
// Actions // Actions
async function fetchUser(reload = true) { async function fetchUser(reload = true): Promise<void> {
if (isLoading.value) { if (currentFetchPromise.value) {
console.log("[UserStore] Fetch already in progress. Skipping.") console.log("[UserStore] Fetch already in progress. Waiting for existing fetch.")
return return currentFetchPromise.value
} }
if (!reload && user.value) { if (!reload && user.value) {
console.log( console.log(
`[UserStore] User store was loaded with account @${user.value.name} and no reload. Skipping.` `[UserStore] User store was loaded with account @${user.value.name} and no reload. Skipping.`
) )
return return Promise.resolve()
} }
isLoading.value = true const fetchPromise = (async () => {
error.value = null isLoading.value = true
const api = useSolarNetwork() error.value = null
try { const api = useSolarNetwork()
const response = await api<SnAccount>("/id/accounts/me") try {
console.log("[UserStore] Fetched user data: ", response) const response = await api<SnAccount>("/id/accounts/me")
user.value = response user.value = response
console.log(`[UserStore] Logged in as @${user.value.name}`) console.log(`[UserStore] Logged in as @${user.value.name}`)
} catch (e: unknown) { } catch (e: unknown) {
if (e instanceof FetchError && e.statusCode == 401) { if (e instanceof FetchError && e.statusCode == 401) {
error.value = "Unauthorized" error.value = "Unauthorized"
user.value = null user.value = null
} else { } else {
error.value = e instanceof Error ? e.message : "An error occurred" error.value = e instanceof Error ? e.message : "An error occurred"
user.value = null // Clear user data on error user.value = null // Clear user data on error
console.error("Failed to fetch user... ", e) 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() { function logout() {