Commit 9dda9979 authored by Dannon Baker's avatar Dannon Baker
Browse files

Refactor user loading logic to use a single promise, ensuring multiple callers...

Refactor user loading logic to use a single promise, ensuring multiple callers can await the same load operation without clearing the promise.
parent 9d8a696d
Loading
Loading
Loading
Loading
+29 −22
Original line number Diff line number Diff line
@@ -70,8 +70,12 @@ export const useUserStore = defineStore("userStore", () => {

    function loadUser(includeHistories = true) {
        if (!loadPromise) {
            loadPromise = getCurrentUser()
                .then(async (user) => {
            loadPromise = new Promise<void>((resolve, reject) => {
                (async () => {
                    console.debug("Loading once");
                    try {
                        const user = await getCurrentUser();

                        if (isRegisteredUser(user)) {
                            currentUser.value = user;
                            currentPreferences.value = processUserPreferences(user);
@@ -80,20 +84,23 @@ export const useUserStore = defineStore("userStore", () => {
                        } else if (user === null) {
                            currentUser.value = null;
                        }

                        if (includeHistories) {
                            const historyStore = useHistoryStore();
                        // load first few histories for user to start pagination
                            await historyStore.loadHistories();
                        }
                })
                .catch((e) => {
                        resolve(); // Resolve the promise after successful load
                    } catch (e) {
                        console.error("Failed to load user", e);
                })
                .finally(() => {
                    loadPromise = null;
                        reject(e); // Reject the promise on error
                    } finally {
                        //Don't clear the loadPromise, we still want multiple callers to await.
                        //Instead we must clear it upon $reset
                        // loadPromise = null;
                    }
                })();
            });
        }
        return loadPromise; // Return the shared promise
    }

    async function setCurrentTheme(theme: string) {