Skip to content

Commit

Permalink
perf: improved state persistence logic by preventing redundant saves …
Browse files Browse the repository at this point in the history
…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`.
  • Loading branch information
stephenjason89 authored Jan 12, 2025
1 parent 0d8aac2 commit 620afad
Showing 1 changed file with 8 additions and 2 deletions.
10 changes: 8 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,9 @@ export function createStatePersistence<S extends StateTree = StateTree>(
}

// 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<void>[] = []
Expand Down Expand Up @@ -137,10 +138,15 @@ export function createStatePersistence<S extends StateTree = StateTree>(
}
}
}
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)

Expand Down

0 comments on commit 620afad

Please sign in to comment.