Skip to content
Myr

fix(persist): clearStorage() should invalidate concurrent async rehydration (#3555)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* fix(persist): advance hydrationVersion in clearStorage to prevent stale async hydration Addresses https://github.com/pmndrs/zustand/discussions/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 <490574+dai-shi@users.noreply.github.com> * fix: correct import order in persistAsync.test.tsx Co-authored-by: dai-shi <490574+dai-shi@users.noreply.github.com> * chore: remove package-lock.json (project uses pnpm) Co-authored-by: dai-shi <490574+dai-shi@users.noreply.github.com> ---------

authored by Copilot · committed by GitHub · parent f44cecc · Browse files · 2 files+180 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
  • Co-authored-by: dai-shi <490574+dai-shi@users.noreply.github.com>
  • Co-authored-by: Daishi Kato <dai-shi@users.noreply.github.com>

Diff stats

2 files+180 added−0 removed

  • tests:+179 added−0 removed
  • other:+1 added−0 removed

2 files+180 added−0 removed

modified:src/middleware/persist.ts+1 added
344 unmodified lines
345 storage = newOptions.storage346 }347 },348 clearStorage: () => {349 ++hydrationVersion350 storage?.removeItem(options.name)351 },352 getOptions: () => options,353 rehydrate: () => hydrate() as Promise<void>,
50 unmodified lines
modified:tests/persistAsync.test.tsx+179 added
3 unmodified lines
4import { act, render, screen } from '@testing-library/react'5import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'6import { create } from 'zustand'7import { createJSONStorage, persist } from 'zustand/middleware'8import { createStore } from 'zustand/vanilla'9import { replacer, reviver, sleep } from './test-utils'1011const createPersistantStore = (initialValue: string | null) => {12 let state = initialValue
1050 unmodified lines
1063 // Final state should be from second hydration's migration1064 expect(useBoundStore.getState().count).toBe(10)1065 })1066})10671068type Deferred<T> = {1069 promise: Promise<T>1070 resolve: (value: T) => void1071}10721073const deferred = <T,>(): Deferred<T> => {1074 let resolve!: (value: T) => void1075 const promise = new Promise<T>((resolvePromise) => {1076 resolve = resolvePromise1077 })1078 return { promise, resolve }1079}10801081describe('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: number1086 } | 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 )10991100 const hydration = store.persist.rehydrate()1101 store.persist.clearStorage()1102 storedValue.resolve({ state: { count: 1 }, version: 0 })1103 await hydration11041105 expect(removeItem).toHaveBeenCalledTimes(1)1106 expect(store.getState().count).toBe(0)1107 })11081109 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 )11261127 const hydration = store.persist.rehydrate()1128 expect(migrate).toHaveBeenCalledWith({ count: 1 }, 1)1129 store.persist.clearStorage()1130 migratedValue.resolve({ count: 2 })1131 await hydration11321133 expect(removeItem).toHaveBeenCalledTimes(1)1134 expect(store.getState().count).toBe(0)1135 })11361137 it('revokes the active hydration even when storage removal throws', async () => {1138 const olderValue = deferred<{1139 state: { count: number }1140 version: number1141 } | null>()1142 const removeError = new Error('remove failed')1143 let readCount = 01144 const store = createStore(1145 persist(() => ({ count: 0 }), {1146 name: 'test-storage',1147 skipHydration: true,1148 storage: {1149 getItem: () => {1150 readCount += 11151 return readCount === 11152 ? olderValue.promise1153 : { state: { count: 2 }, version: 0 }1154 },1155 removeItem: () => {1156 throw removeError1157 },1158 setItem: () => {},1159 },1160 }),1161 )11621163 const olderHydration = store.persist.rehydrate()1164 expect(() => store.persist.clearStorage()).toThrow(removeError)1165 olderValue.resolve({ state: { count: 1 }, version: 0 })1166 await olderHydration11671168 expect(store.getState().count).toBe(0)11691170 await store.persist.rehydrate()1171 expect(store.getState().count).toBe(2)1172 })11731174 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 )11871188 await store.persist.rehydrate()1189 store.persist.clearStorage()11901191 expect(removeItem).toHaveBeenCalledTimes(1)1192 expect(store.getState().count).toBe(1)1193 })11941195 it('suppresses stale completion signals and allows a later hydration', async () => {1196 const olderValue = deferred<{1197 state: { count: number }1198 version: number1199 } | null>()1200 const postRehydrationCallback = vi.fn()1201 const finishHydrationListener = vi.fn()1202 let readCount = 01203 const store = createStore(1204 persist(() => ({ count: 0 }), {1205 name: 'test-storage',1206 onRehydrateStorage: () => postRehydrationCallback,1207 skipHydration: true,1208 storage: {1209 getItem: () => {1210 readCount += 11211 return readCount === 11212 ? olderValue.promise1213 : { state: { count: 2 }, version: 0 }1214 },1215 removeItem: () => {},1216 setItem: () => {},1217 },1218 }),1219 )1220 store.persist.onFinishHydration(finishHydrationListener)12211222 const olderHydration = store.persist.rehydrate()1223 store.persist.clearStorage()1224 olderValue.resolve({ state: { count: 1 }, version: 0 })1225 await olderHydration12261227 expect(store.getState().count).toBe(0)1228 expect(store.persist.hasHydrated()).toBe(false)1229 expect(postRehydrationCallback).not.toHaveBeenCalled()1230 expect(finishHydrationListener).not.toHaveBeenCalled()12311232 await store.persist.rehydrate()12331234 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})