Skip to content

Commit 3febf8c

Browse files
Copilotdai-shi
andauthored
fix(persist): clearStorage() should invalidate concurrent async rehydration (#3555)
* fix(persist): advance hydrationVersion in clearStorage to prevent stale async hydration Addresses #3554 When clearStorage() is called while an async rehydrate() is still pending, the storage item gets removed but the older read can finish afterward and apply the value that was just cleared. Fix: increment hydrationVersion in clearStorage() so any in-flight hydration is treated as stale and discarded, consistent with how concurrent rehydrate() calls are already handled. Co-authored-by: dai-shi <[email protected]> * fix: correct import order in persistAsync.test.tsx Co-authored-by: dai-shi <[email protected]> * chore: remove package-lock.json (project uses pnpm) Co-authored-by: dai-shi <[email protected]> --------- Co-authored-by: copilot-swe-agent[bot] <[email protected]> Co-authored-by: dai-shi <[email protected]> Co-authored-by: Daishi Kato <[email protected]>
1 parent f44cecc commit 3febf8c

2 files changed

Lines changed: 180 additions & 0 deletions

File tree

‎src/middleware/persist.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -346,6 +346,7 @@ const persistImpl: PersistImpl = (config, baseOptions) => (set, get, api) => {
346346
}
347347
},
348348
clearStorage: () => {
349+
++hydrationVersion
349350
storage?.removeItem(options.name)
350351
},
351352
getOptions: () => options,

‎tests/persistAsync.test.tsx‎

Lines changed: 179 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { act, render, screen } from '@testing-library/react'
55
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
66
import { create } from 'zustand'
77
import { createJSONStorage, persist } from 'zustand/middleware'
8+
import { createStore } from 'zustand/vanilla'
89
import { replacer, reviver, sleep } from './test-utils'
910

1011
const createPersistantStore = (initialValue: string | null) => {
@@ -1063,3 +1064,181 @@ describe('persist middleware with async configuration', () => {
10631064
expect(useBoundStore.getState().count).toBe(10)
10641065
})
10651066
})
1067+
1068+
type Deferred<T> = {
1069+
promise: Promise<T>
1070+
resolve: (value: T) => void
1071+
}
1072+
1073+
const deferred = <T,>(): Deferred<T> => {
1074+
let resolve!: (value: T) => void
1075+
const promise = new Promise<T>((resolvePromise) => {
1076+
resolve = resolvePromise
1077+
})
1078+
return { promise, resolve }
1079+
}
1080+
1081+
describe('persist clearStorage hydration generation', () => {
1082+
it('keeps a cleared delayed stored value from hydrating state', async () => {
1083+
const storedValue = deferred<{
1084+
state: { count: number }
1085+
version: number
1086+
} | null>()
1087+
const removeItem = vi.fn()
1088+
const store = createStore(
1089+
persist(() => ({ count: 0 }), {
1090+
name: 'test-storage',
1091+
skipHydration: true,
1092+
storage: {
1093+
getItem: () => storedValue.promise,
1094+
removeItem,
1095+
setItem: () => {},
1096+
},
1097+
}),
1098+
)
1099+
1100+
const hydration = store.persist.rehydrate()
1101+
store.persist.clearStorage()
1102+
storedValue.resolve({ state: { count: 1 }, version: 0 })
1103+
await hydration
1104+
1105+
expect(removeItem).toHaveBeenCalledTimes(1)
1106+
expect(store.getState().count).toBe(0)
1107+
})
1108+
1109+
it('keeps a cleared delayed migration from hydrating state', async () => {
1110+
const migratedValue = deferred<{ count: number }>()
1111+
const migrate = vi.fn(() => migratedValue.promise)
1112+
const removeItem = vi.fn()
1113+
const store = createStore(
1114+
persist(() => ({ count: 0 }), {
1115+
migrate,
1116+
name: 'test-storage',
1117+
skipHydration: true,
1118+
storage: {
1119+
getItem: () => ({ state: { count: 1 }, version: 1 }),
1120+
removeItem,
1121+
setItem: () => {},
1122+
},
1123+
version: 2,
1124+
}),
1125+
)
1126+
1127+
const hydration = store.persist.rehydrate()
1128+
expect(migrate).toHaveBeenCalledWith({ count: 1 }, 1)
1129+
store.persist.clearStorage()
1130+
migratedValue.resolve({ count: 2 })
1131+
await hydration
1132+
1133+
expect(removeItem).toHaveBeenCalledTimes(1)
1134+
expect(store.getState().count).toBe(0)
1135+
})
1136+
1137+
it('revokes the active hydration even when storage removal throws', async () => {
1138+
const olderValue = deferred<{
1139+
state: { count: number }
1140+
version: number
1141+
} | null>()
1142+
const removeError = new Error('remove failed')
1143+
let readCount = 0
1144+
const store = createStore(
1145+
persist(() => ({ count: 0 }), {
1146+
name: 'test-storage',
1147+
skipHydration: true,
1148+
storage: {
1149+
getItem: () => {
1150+
readCount += 1
1151+
return readCount === 1
1152+
? olderValue.promise
1153+
: { state: { count: 2 }, version: 0 }
1154+
},
1155+
removeItem: () => {
1156+
throw removeError
1157+
},
1158+
setItem: () => {},
1159+
},
1160+
}),
1161+
)
1162+
1163+
const olderHydration = store.persist.rehydrate()
1164+
expect(() => store.persist.clearStorage()).toThrow(removeError)
1165+
olderValue.resolve({ state: { count: 1 }, version: 0 })
1166+
await olderHydration
1167+
1168+
expect(store.getState().count).toBe(0)
1169+
1170+
await store.persist.rehydrate()
1171+
expect(store.getState().count).toBe(2)
1172+
})
1173+
1174+
it('does not reset live state when clearing after hydration', async () => {
1175+
const removeItem = vi.fn()
1176+
const store = createStore(
1177+
persist(() => ({ count: 0 }), {
1178+
name: 'test-storage',
1179+
skipHydration: true,
1180+
storage: {
1181+
getItem: () => ({ state: { count: 1 }, version: 0 }),
1182+
removeItem,
1183+
setItem: () => {},
1184+
},
1185+
}),
1186+
)
1187+
1188+
await store.persist.rehydrate()
1189+
store.persist.clearStorage()
1190+
1191+
expect(removeItem).toHaveBeenCalledTimes(1)
1192+
expect(store.getState().count).toBe(1)
1193+
})
1194+
1195+
it('suppresses stale completion signals and allows a later hydration', async () => {
1196+
const olderValue = deferred<{
1197+
state: { count: number }
1198+
version: number
1199+
} | null>()
1200+
const postRehydrationCallback = vi.fn()
1201+
const finishHydrationListener = vi.fn()
1202+
let readCount = 0
1203+
const store = createStore(
1204+
persist(() => ({ count: 0 }), {
1205+
name: 'test-storage',
1206+
onRehydrateStorage: () => postRehydrationCallback,
1207+
skipHydration: true,
1208+
storage: {
1209+
getItem: () => {
1210+
readCount += 1
1211+
return readCount === 1
1212+
? olderValue.promise
1213+
: { state: { count: 2 }, version: 0 }
1214+
},
1215+
removeItem: () => {},
1216+
setItem: () => {},
1217+
},
1218+
}),
1219+
)
1220+
store.persist.onFinishHydration(finishHydrationListener)
1221+
1222+
const olderHydration = store.persist.rehydrate()
1223+
store.persist.clearStorage()
1224+
olderValue.resolve({ state: { count: 1 }, version: 0 })
1225+
await olderHydration
1226+
1227+
expect(store.getState().count).toBe(0)
1228+
expect(store.persist.hasHydrated()).toBe(false)
1229+
expect(postRehydrationCallback).not.toHaveBeenCalled()
1230+
expect(finishHydrationListener).not.toHaveBeenCalled()
1231+
1232+
await store.persist.rehydrate()
1233+
1234+
expect(store.getState().count).toBe(2)
1235+
expect(store.persist.hasHydrated()).toBe(true)
1236+
expect(postRehydrationCallback).toHaveBeenCalledExactlyOnceWith(
1237+
{ count: 2 },
1238+
undefined,
1239+
)
1240+
expect(finishHydrationListener).toHaveBeenCalledExactlyOnceWith({
1241+
count: 2,
1242+
})
1243+
})
1244+
})

0 commit comments

Comments
 (0)