Skip to content

Commit

Permalink
feat: persist data once or less in each 500ms
Browse files Browse the repository at this point in the history
  • Loading branch information
clement2026 committed Sep 23, 2023
1 parent 40966e5 commit ae5a03c
Showing 1 changed file with 18 additions and 12 deletions.
30 changes: 18 additions & 12 deletions src/state/app-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ export const hydrationState = proxy({
hydrated: false
})

export const persistState = proxy({
changedAt: Date.now(),
})

export const appState = proxy<AppState>({
version: packageJson.version,
auth: {
Expand Down Expand Up @@ -91,7 +95,7 @@ export const resetAppState = () => {
console.debug("resetting appState, key:", key)
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
appState[key as keyof AppState] = dft[key]
appState[key as keyof AppState] = dft[key]
})
}

Expand All @@ -115,20 +119,22 @@ appDb.getItem<AppState>(appStateKey).then((as: AppState | null) => {
hydrationState.hydrated = true
})


subscribe(appState, () => {
const hySnp = snapshot(hydrationState)
if (!hySnp.hydrated) {
// never write to the state before hydration, or state in indexeddb will be overwritten by default state
console.debug("skipping subscription due to not hydrated")
return
}
const as = snapshot(appState)
// console.debug("saving appState:", as)
appDb.setItem(appStateKey, as).then(() => {
console.debug("appState saved")
})
persistState.changedAt = Date.now()
})

setInterval(() => {
if (Date.now() - persistState.changedAt < 500 && hydrationState.hydrated) {
const as = snapshot(appState)
// console.debug("saving appState:", as)
appDb.setItem(appStateKey, as).then(() => {
console.debug("appState saved")
})
}
}, 500)


export const clearSettings = () => {
const dft = defaultAppState()
appState.auth = dft.auth
Expand Down

0 comments on commit ae5a03c

Please sign in to comment.