🐛 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,29 +9,30 @@ 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()
} }
const fetchPromise = (async () => {
isLoading.value = true isLoading.value = true
error.value = null error.value = null
const api = useSolarNetwork() const api = useSolarNetwork()
try { try {
const response = await api<SnAccount>("/id/accounts/me") const response = await api<SnAccount>("/id/accounts/me")
console.log("[UserStore] Fetched user data: ", response)
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) {
@@ -45,7 +46,12 @@ export const useUserStore = defineStore("user", () => {
} }
} finally { } finally {
isLoading.value = false isLoading.value = false
currentFetchPromise.value = null
} }
})()
currentFetchPromise.value = fetchPromise
return fetchPromise
} }
function logout() { function logout() {