From 620afad39806e7277c03d92c0b80b2735e3df680 Mon Sep 17 00:00:00 2001 From: Stephen Jason Wang Date: Sun, 12 Jan 2025 22:14:57 +0800 Subject: [PATCH] perf: improved state persistence logic by preventing redundant saves when the state hasn't changed (#7) - Added `lastPersistedState` with type `S | undefined` to track the last persisted state. - Ensured `lastPersistedState` is reset to `undefined` during state restoration in `$restore`. --- src/index.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/index.ts b/src/index.ts index 9384091..c02a763 100644 --- a/src/index.ts +++ b/src/index.ts @@ -107,8 +107,9 @@ export function createStatePersistence( } // Persist state on mutation + let lastPersistedState: S | undefined const persistState = (mutation: any, state: S) => { - if (!filter(mutation, state)) + if (!filter(mutation, state) || lastPersistedState === state) return const tasks: Promise[] = [] @@ -137,10 +138,15 @@ export function createStatePersistence( } } } + lastPersistedState = state return tasks.length ? Promise.all(tasks) : undefined } - context.store.$restore = loadState + context.store.$restore = () => { + loadState() + lastPersistedState = undefined + } + context.store.$persist = () => persistState({ type: 'persist', storeId: context.store.$id }, context.store.$state)