From 9c66f62408cf17e3a812e0cc56e719443f463df4 Mon Sep 17 00:00:00 2001 From: KoloMl Date: Sat, 10 Aug 2024 13:53:19 +0400 Subject: [PATCH] Wait for initial loading before subscribing to changes --- src/stores/maintenance-profiles-store.js | 53 +++++++++++++----------- 1 file changed, 28 insertions(+), 25 deletions(-) diff --git a/src/stores/maintenance-profiles-store.js b/src/stores/maintenance-profiles-store.js index ffc0db1..792d212 100644 --- a/src/stores/maintenance-profiles-store.js +++ b/src/stores/maintenance-profiles-store.js @@ -9,14 +9,6 @@ import MaintenanceSettings from "$lib/extension/settings/MaintenanceSettings.js" */ export const maintenanceProfilesStore = writable([]); -MaintenanceProfile.readAll().then(profiles => { - maintenanceProfilesStore.set(profiles); -}); - -MaintenanceProfile.subscribe(profiles => { - maintenanceProfilesStore.set(profiles); -}); - /** * Store for the active maintenance profile ID. * @@ -26,29 +18,40 @@ export const activeProfileStore = writable(null); const maintenanceSettings = new MaintenanceSettings(); -maintenanceSettings.resolveActiveProfileId().then(activeProfileId => { - activeProfileStore.set(activeProfileId); -}); - -maintenanceSettings.subscribe(settings => { - activeProfileStore.set(settings.activeProfile || null); -}); - /** * Active profile ID stored locally. Used to reset active profile once the existing profile was removed. * @type {string|null} */ let lastActiveProfileId = null; -activeProfileStore.subscribe(profileId => { - lastActiveProfileId = profileId; +Promise.allSettled([ + // Read the initial values from the storages first + MaintenanceProfile.readAll().then(profiles => { + maintenanceProfilesStore.set(profiles); + }), + maintenanceSettings.resolveActiveProfileId().then(activeProfileId => { + activeProfileStore.set(activeProfileId); + }) +]).then(() => { + // And only after initial values are loaded, start watching for changes from storage and from user's interaction + MaintenanceProfile.subscribe(profiles => { + maintenanceProfilesStore.set(profiles); + }); - void maintenanceSettings.setActiveProfileId(profileId); -}); + maintenanceSettings.subscribe(settings => { + activeProfileStore.set(settings.activeProfile || null); + }); -// Watch the existence of the active profile on every change. -MaintenanceProfile.subscribe(profiles => { - if (!profiles.find(profile => profile.id === lastActiveProfileId)) { - activeProfileStore.set(null); - } + activeProfileStore.subscribe(profileId => { + lastActiveProfileId = profileId; + + void maintenanceSettings.setActiveProfileId(profileId); + }); + + // Watch the existence of the active profile on every change. + MaintenanceProfile.subscribe(profiles => { + if (!profiles.find(profile => profile.id === lastActiveProfileId)) { + activeProfileStore.set(null); + } + }); });