diff --git a/src/utils/storeManager.ts b/src/utils/storeManager.ts index 18fcc4799..2f4f1cf56 100644 --- a/src/utils/storeManager.ts +++ b/src/utils/storeManager.ts @@ -22,31 +22,35 @@ export function hasStateChanged(prevState: T, updates: Partial): boolean { }); } +interface StoreSetStateJob { + partial: Partial | ((state: T) => Partial); + force?: boolean; +} + /** * A custom store creation utility */ export function createStore(initialState: T): Store { let state = { ...initialState }; + const queue: StoreSetStateJob[] = []; const listeners = new Set<() => void>(); - let isUpdating = false; - - const setState = (partial: Partial | ((state: T) => Partial), force?: boolean) => { - // Prevent nested updates - if (isUpdating) return; - try { - isUpdating = true; - const nextState = typeof partial === 'function' ? partial(state) : partial; - const hasChanged = hasStateChanged(state, nextState); + const processQueue = () => { + const job = queue.shift(); + if (!job) return; - if (force || hasChanged) { - state = { ...state, ...nextState }; - listeners.forEach((listener) => listener()); - } - } finally { - isUpdating = false; + const { partial, force } = job; + const nextState = typeof partial === 'function' ? partial(state) : partial; + const hasChanged = hasStateChanged(state, nextState); + if (force || hasChanged) { + state = { ...state, ...nextState }; + listeners.forEach((listener) => listener()); } }; + const setState = (partial: Partial | ((state: T) => Partial), force?: boolean) => { + queue.push({ partial, force }); + processQueue(); + }; return { getState: () => state,