persistAsync.test.tsx
This file
Path
tests/persistAsync.test.tsx
1,244 lines · 32.4 KiB · TypeScript
Last changed by
fix(persist): clearStorage() should invalidate concurrent async rehydration (#3555)Copilotbefore adoption3febf8c
History of this fileTake it
The walk stopped after 200 commits: lines older than f85898f point at it.
chore: update dev dependencies (#3279)Daishi Katobefore adoption18ab9e2
lines 1–2why, one step back1/// <reference types="node" />2chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
line 3why, one step back3import { StrictMode, useEffect } from 'react'test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 4–5why, one step back4import { act, render, screen } from '@testing-library/react'5import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 6–7why, one step back6import { create } from 'zustand'7import { createJSONStorage, persist } from 'zustand/middleware'fix(persist): clearStorage() should invalidate concurrent async rehydration (#3555)Copilotbefore adoption3febf8c
line 8why, one step back8import { createStore } from 'zustand/vanilla'test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
line 9why, one step back9import { replacer, reviver, sleep } from './test-utils'chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 10–15why, one step back1011const createPersistantStore = (initialValue: string | null) => {12 let state = initialValue1314 const getItem = async (): Promise<string | null> => {15 getItemSpy()test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
line 16why, one step back16 await sleep(10)chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 17–20why, one step back17 return state18 }19 const setItem = async (name: string, newState: string) => {20 setItemSpy(name, newState)test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
line 21why, one step back21 await sleep(10)chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 22–26why, one step back22 state = newState23 }2425 const removeItem = async (name: string) => {26 removeItemSpy(name)test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
line 27why, one step back27 await sleep(10)chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 28–44why, one step back28 state = null29 }3031 const getItemSpy = vi.fn()32 const setItemSpy = vi.fn()33 const removeItemSpy = vi.fn()3435 return {36 storage: { getItem, setItem, removeItem },37 getItemSpy,38 setItemSpy,39 removeItemSpy,40 }41}4243describe('persist middleware with async configuration', () => {44 const consoleError = console.errortest: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 45–49why, one step back4546 beforeEach(() => {47 vi.useFakeTimers()48 })49chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
line 50why, one step back50 afterEach(() => {test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
line 51why, one step back51 vi.useRealTimers()chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 52–57why, one step back52 console.error = consoleError53 })5455 it('can rehydrate state', async () => {56 const onRehydrateStorageSpy = vi.fn()57 const storage = {test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 58–60why, one step back58 getItem: async (name: string) => {59 await sleep(10)60 return JSON.stringify({chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 61–62why, one step back61 state: { count: 42, name },62 version: 0,test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 63–64why, one step back63 })64 },chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 65–97why, one step back65 setItem: () => {},66 removeItem: () => {},67 }6869 const useBoundStore = create(70 persist(71 () => ({72 count: 0,73 name: 'empty',74 }),75 {76 name: 'test-storage',77 storage: createJSONStorage(() => storage),78 onRehydrateStorage: () => onRehydrateStorageSpy,79 },80 ),81 )8283 function Counter() {84 const { count, name } = useBoundStore()85 return (86 <div>87 count: {count}, name: {name}88 </div>89 )90 }9192 render(93 <StrictMode>94 <Counter />95 </StrictMode>,96 )97test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 98–99why, one step back98 expect(screen.getByText('count: 0, name: empty')).toBeInTheDocument()99 await act(() => vi.advanceTimersByTimeAsync(10))test(*): add 'expect' with 'toBeInTheDocument' (#3162)Wonsuk Choibefore adoption295bf97
line 100why, one step back100 expect(test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
line 101why, one step back101 screen.getByText('count: 42, name: test-storage'),test(*): add 'expect' with 'toBeInTheDocument' (#3162)Wonsuk Choibefore adoption295bf97
line 102why, one step back102 ).toBeInTheDocument()test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
line 103why, one step back103 expect(onRehydrateStorageSpy).toHaveBeenCalledWith(chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 104–113why, one step back104 { count: 42, name: 'test-storage' },105 undefined,106 )107 })108109 it('can throw rehydrate error', async () => {110 const onRehydrateStorageSpy = vi.fn()111112 const storage = {113 getItem: async () => {test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
line 114why, one step back114 await sleep(10)chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 115–139why, one step back115 throw new Error('getItem error')116 },117 setItem: () => {},118 removeItem: () => {},119 }120121 const useBoundStore = create(122 persist(() => ({ count: 0 }), {123 name: 'test-storage',124 storage: createJSONStorage(() => storage),125 onRehydrateStorage: () => onRehydrateStorageSpy,126 }),127 )128129 function Counter() {130 const { count } = useBoundStore()131 return <div>count: {count}</div>132 }133134 render(135 <StrictMode>136 <Counter />137 </StrictMode>,138 )139test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 140–145why, one step back140 expect(screen.getByText('count: 0')).toBeInTheDocument()141 await act(() => vi.advanceTimersByTimeAsync(10))142 expect(onRehydrateStorageSpy).toHaveBeenCalledWith(143 undefined,144 new Error('getItem error'),145 )chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 146–176why, one step back146 })147148 it('can persist state', async () => {149 const { storage, setItemSpy } = createPersistantStore(null)150151 const createStore = () => {152 const onRehydrateStorageSpy = vi.fn()153 const useBoundStore = create(154 persist(() => ({ count: 0 }), {155 name: 'test-storage',156 storage: createJSONStorage(() => storage),157 onRehydrateStorage: () => onRehydrateStorageSpy,158 }),159 )160 return { useBoundStore, onRehydrateStorageSpy }161 }162163 // Initialize from empty storage164 const { useBoundStore, onRehydrateStorageSpy } = createStore()165166 function Counter() {167 const { count } = useBoundStore()168 return <div>count: {count}</div>169 }170171 render(172 <StrictMode>173 <Counter />174 </StrictMode>,175 )176test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 177–179why, one step back177 expect(screen.getByText('count: 0')).toBeInTheDocument()178 await act(() => vi.advanceTimersByTimeAsync(10))179 expect(onRehydrateStorageSpy).toHaveBeenCalledWith({ count: 0 }, undefined)chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 180–181why, one step back180181 // Write something to the storefeat(middleare/persist): return storage promise from setState (#3206)Daishi Katobefore adoptionfeddc0c
lines 182–184why, one step back182 act(() => {183 useBoundStore.setState({ count: 42 })184 })test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 185–186why, one step back185 expect(screen.getByText('count: 42')).toBeInTheDocument()186 expect(setItemSpy).toHaveBeenCalledWith(chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 187–198why, one step back187 'test-storage',188 JSON.stringify({ state: { count: 42 }, version: 0 }),189 )190191 // Create the same store a second time and check if the persisted state192 // is loaded correctly193 const {194 useBoundStore: useBoundStore2,195 onRehydrateStorageSpy: onRehydrateStorageSpy2,196 } = createStore()197 function Counter2() {198 const { count } = useBoundStore2()test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
line 199why, one step back199 return <div>count2: {count}</div>chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 200–207why, one step back200 }201202 render(203 <StrictMode>204 <Counter2 />205 </StrictMode>,206 )207test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 208–213why, one step back208 await act(() => vi.advanceTimersByTimeAsync(10))209 expect(screen.getByText('count2: 42')).toBeInTheDocument()210 expect(onRehydrateStorageSpy2).toHaveBeenCalledWith(211 { count: 42 },212 undefined,213 )chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 214–218why, one step back214 })215216 it('can async migrate persisted state', async () => {217 const setItemSpy = vi.fn()218 const onRehydrateStorageSpy = vi.fn()test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 219–222why, one step back219 const migrateSpy = vi.fn(async () => {220 await sleep(10)221 return { count: 99 }222 })chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 223–224why, one step back223224 const storage = {test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 225–227why, one step back225 getItem: async () => {226 await sleep(10)227 return JSON.stringify({chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 228–229why, one step back228 state: { count: 42 },229 version: 12,test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 230–231why, one step back230 })231 },chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 232–256why, one step back232 setItem: setItemSpy,233 removeItem: () => {},234 }235236 const useBoundStore = create(237 persist(() => ({ count: 0 }), {238 name: 'test-storage',239 version: 13,240 storage: createJSONStorage(() => storage),241 onRehydrateStorage: () => onRehydrateStorageSpy,242 migrate: migrateSpy,243 }),244 )245246 function Counter() {247 const { count } = useBoundStore()248 return <div>count: {count}</div>249 }250251 render(252 <StrictMode>253 <Counter />254 </StrictMode>,255 )256test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 257–261why, one step back257 expect(screen.getByText('count: 0')).toBeInTheDocument()258 await act(() => vi.advanceTimersByTimeAsync(20))259 expect(screen.getByText('count: 99')).toBeInTheDocument()260 expect(migrateSpy).toHaveBeenCalledWith({ count: 42 }, 12)261 expect(setItemSpy).toHaveBeenCalledWith(chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 262–267why, one step back262 'test-storage',263 JSON.stringify({264 state: { count: 99 },265 version: 13,266 }),267 )test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
line 268why, one step back268 expect(onRehydrateStorageSpy).toHaveBeenCalledWith({ count: 99 }, undefined)chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 269–272why, one step back269 })270271 it('can merge partial persisted state', async () => {272 const storage = {test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 273–275why, one step back273 getItem: async () => {274 await sleep(10)275 return JSON.stringify({chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
line 276why, one step back276 state: { count: 42 },test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 277–278why, one step back277 })278 },chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 279–321why, one step back279 setItem: () => {},280 removeItem: () => {},281 }282283 const useBoundStore = create<{284 count: number285 name: string286 setName: (name: string) => void287 }>()(288 persist(289 (set) => ({290 count: 0,291 name: 'unknown',292 setName: (name: string) => {293 set({ name })294 },295 }),296 {297 name: 'test-storage',298 storage: createJSONStorage(() => storage),299 },300 ),301 )302303 function Component() {304 const { count, setName, name } = useBoundStore()305 useEffect(() => {306 setName('test')307 }, [setName])308 return (309 <div>310 <div>count: {count}</div>311 <div>name: {name}</div>312 </div>313 )314 }315316 render(317 <StrictMode>318 <Component />319 </StrictMode>,320 )321test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 322–324why, one step back322 await act(() => vi.advanceTimersByTimeAsync(10))323 expect(screen.getByText('count: 42')).toBeInTheDocument()324 expect(screen.getByText('name: test')).toBeInTheDocument()chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 325–333why, one step back325326 expect(useBoundStore.getState()).toEqual(327 expect.objectContaining({328 count: 42,329 name: 'test',330 }),331 )332 })333chore: fix some typos in comment (#3139)clonemycodebefore adoption9d58820
line 334why, one step back334 it('can correctly handle a missing migrate function', async () => {chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 335–337why, one step back335 console.error = vi.fn()336 const onRehydrateStorageSpy = vi.fn()337 const storage = {test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 338–340why, one step back338 getItem: async () => {339 await sleep(10)340 return JSON.stringify({chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 341–342why, one step back341 state: { count: 42 },342 version: 12,test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 343–344why, one step back343 })344 },chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 345–368why, one step back345 setItem: (_: string, _value: string) => {},346 removeItem: () => {},347 }348349 const useBoundStore = create(350 persist(() => ({ count: 0 }), {351 name: 'test-storage',352 version: 13,353 storage: createJSONStorage(() => storage),354 onRehydrateStorage: () => onRehydrateStorageSpy,355 }),356 )357358 function Counter() {359 const { count } = useBoundStore()360 return <div>count: {count}</div>361 }362363 render(364 <StrictMode>365 <Counter />366 </StrictMode>,367 )368test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 369–372why, one step back369 expect(screen.getByText('count: 0')).toBeInTheDocument()370 await act(() => vi.advanceTimersByTimeAsync(10))371 expect(console.error).toHaveBeenCalled()372 expect(onRehydrateStorageSpy).toHaveBeenCalledWith({ count: 0 }, undefined)chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 373–379why, one step back373 })374375 it('can throw migrate error', async () => {376 console.error = vi.fn()377 const onRehydrateStorageSpy = vi.fn()378379 const storage = {test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 380–382why, one step back380 getItem: async () => {381 await sleep(10)382 return JSON.stringify({chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 383–384why, one step back383 state: {},384 version: 12,test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 385–386why, one step back385 })386 },chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 387–413why, one step back387 setItem: () => {},388 removeItem: () => {},389 }390391 const useBoundStore = create(392 persist(() => ({ count: 0 }), {393 name: 'test-storage',394 version: 13,395 storage: createJSONStorage(() => storage),396 migrate: () => {397 throw new Error('migrate error')398 },399 onRehydrateStorage: () => onRehydrateStorageSpy,400 }),401 )402403 function Counter() {404 const { count } = useBoundStore()405 return <div>count: {count}</div>406 }407408 render(409 <StrictMode>410 <Counter />411 </StrictMode>,412 )413test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 414–419why, one step back414 expect(screen.getByText('count: 0')).toBeInTheDocument()415 await act(() => vi.advanceTimersByTimeAsync(10))416 expect(onRehydrateStorageSpy).toHaveBeenCalledWith(417 undefined,418 new Error('migrate error'),419 )chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 420–425why, one step back420 })421422 it('passes the latest state to onRehydrateStorage and onHydrate on first hydrate', async () => {423 const onRehydrateStorageSpy = vi.fn()424425 const storage = {test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 426–429why, one step back426 getItem: async () => {427 await sleep(10)428 return JSON.stringify({ state: { count: 1 } })429 },chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 430–450why, one step back430 setItem: () => {},431 removeItem: () => {},432 }433434 const useBoundStore = create(435 persist(() => ({ count: 0 }), {436 name: 'test-storage',437 storage: createJSONStorage(() => storage),438 onRehydrateStorage: onRehydrateStorageSpy,439 }),440 )441442 /**443 * NOTE: It's currently not possible to add an 'onHydrate' listener which will be444 * invoked prior to the first hydration. This is because, during first hydration,445 * the 'onHydrate' listener set (which will be empty) is evaluated before the446 * 'persist' API is exposed to the caller of 'create'/'createStore'.447 *448 * const onHydrateSpy = vi.fn()449 * useBoundStore.persist.onHydrate(onHydrateSpy)450 * ...test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 451–452why, one step back451 * await act(() => vi.advanceTimersByTimeAsync(10))452 * expect(onHydrateSpy).toHaveBeenCalledWith({ count: 0 })chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 453–465why, one step back453 */454455 function Counter() {456 const { count } = useBoundStore()457 return <div>count: {count}</div>458 }459460 render(461 <StrictMode>462 <Counter />463 </StrictMode>,464 )465test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 466–467why, one step back466 await act(() => vi.advanceTimersByTimeAsync(10))467 expect(screen.getByText('count: 1')).toBeInTheDocument()chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 468–470why, one step back468469 // The 'onRehydrateStorage' spy is invoked prior to rehydration, so it should470 // be passed the default state.test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
line 471why, one step back471 expect(onRehydrateStorageSpy).toHaveBeenCalledWith({ count: 0 })chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 472–477why, one step back472 })473474 it('gives the merged state to onRehydrateStorage', async () => {475 const onRehydrateStorageSpy = vi.fn()476477 const storage = {test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 478–480why, one step back478 getItem: async () => {479 await sleep(10)480 return JSON.stringify({chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 481–482why, one step back481 state: { count: 1 },482 version: 0,test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 483–484why, one step back483 })484 },chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 485–509why, one step back485 setItem: () => {},486 removeItem: () => {},487 }488489 const unstorableMethod = () => {}490491 const useBoundStore = create(492 persist(() => ({ count: 0, unstorableMethod }), {493 name: 'test-storage',494 storage: createJSONStorage(() => storage),495 onRehydrateStorage: () => onRehydrateStorageSpy,496 }),497 )498499 function Counter() {500 const { count } = useBoundStore()501 return <div>count: {count}</div>502 }503504 render(505 <StrictMode>506 <Counter />507 </StrictMode>,508 )509test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 510–515why, one step back510 expect(screen.getByText('count: 0')).toBeInTheDocument()511 await act(() => vi.advanceTimersByTimeAsync(10))512 expect(onRehydrateStorageSpy).toHaveBeenCalledWith(513 { count: 1, unstorableMethod },514 undefined,515 )chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 516–519why, one step back516 })517518 it('can custom merge the stored state', async () => {519 const storage = {test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 520–522why, one step back520 getItem: async () => {521 await sleep(10)522 return JSON.stringify({chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 523–527why, one step back523 state: {524 count: 1,525 actions: {},526 },527 version: 0,test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 528–529why, one step back528 })529 },chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 530–562why, one step back530 setItem: () => {},531 removeItem: () => {},532 }533534 const unstorableMethod = () => {}535536 const useBoundStore = create(537 persist(() => ({ count: 0, actions: { unstorableMethod } }), {538 name: 'test-storage',539 storage: createJSONStorage(() => storage),540 merge: (_persistedState, currentState) => {541 const persistedState = _persistedState as any542 delete persistedState.actions543544 return {545 ...currentState,546 ...persistedState,547 }548 },549 }),550 )551552 function Counter() {553 const { count } = useBoundStore()554 return <div>count: {count}</div>555 }556557 render(558 <StrictMode>559 <Counter />560 </StrictMode>,561 )562test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 563–564why, one step back563 await act(() => vi.advanceTimersByTimeAsync(10))564 expect(screen.getByText('count: 1')).toBeInTheDocument()chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 565–574why, one step back565 expect(useBoundStore.getState()).toEqual({566 count: 1,567 actions: {568 unstorableMethod,569 },570 })571 })572573 it("can merge the state when the storage item doesn't have a version", async () => {574 const storage = {test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 575–577why, one step back575 getItem: async () => {576 await sleep(10)577 return JSON.stringify({chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 578–580why, one step back578 state: {579 count: 1,580 },test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 581–582why, one step back581 })582 },chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 583–604why, one step back583 setItem: () => {},584 removeItem: () => {},585 }586587 const useBoundStore = create(588 persist(() => ({ count: 0 }), {589 name: 'test-storage',590 storage: createJSONStorage(() => storage),591 }),592 )593594 function Counter() {595 const { count } = useBoundStore()596 return <div>count: {count}</div>597 }598599 render(600 <StrictMode>601 <Counter />602 </StrictMode>,603 )604test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 605–606why, one step back605 await act(() => vi.advanceTimersByTimeAsync(10))606 expect(screen.getByText('count: 1')).toBeInTheDocument()chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 607–615why, one step back607 expect(useBoundStore.getState()).toEqual({608 count: 1,609 })610 })611612 it('can manually rehydrate through the api', async () => {613 const storageValue = '{"state":{"count":1},"version":0}'614615 const storage = {test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 616–619why, one step back616 getItem: async () => {617 await sleep(10)618 return ''619 },chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 620–630why, one step back620 setItem: () => {},621 removeItem: () => {},622 }623624 const useBoundStore = create(625 persist(() => ({ count: 0 }), {626 name: 'test-storage',627 storage: createJSONStorage(() => storage),628 }),629 )630test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 631–637why, one step back631 storage.getItem = async () => {632 await sleep(10)633 return storageValue634 }635 const rehydratePromise = useBoundStore.persist.rehydrate()636 await act(() => vi.advanceTimersByTimeAsync(10))637 await rehydratePromisechore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 638–644why, one step back638 expect(useBoundStore.getState()).toEqual({639 count: 1,640 })641 })642643 it('can check if the store has been hydrated through the api', async () => {644 const storage = {test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 645–648why, one step back645 getItem: async () => {646 await sleep(10)647 return null648 },chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 649–659why, one step back649 setItem: () => {},650 removeItem: () => {},651 }652653 const useBoundStore = create(654 persist(() => ({ count: 0 }), {655 name: 'test-storage',656 storage: createJSONStorage(() => storage),657 }),658 )659 expect(useBoundStore.persist.hasHydrated()).toBe(false)test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
line 660why, one step back660 await act(() => vi.advanceTimersByTimeAsync(10))chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 661–662why, one step back661 expect(useBoundStore.persist.hasHydrated()).toBe(true)662test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 663–665why, one step back663 const rehydratePromise = useBoundStore.persist.rehydrate()664 await act(() => vi.advanceTimersByTimeAsync(10))665 await rehydratePromisechore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 666–670why, one step back666 expect(useBoundStore.persist.hasHydrated()).toBe(true)667 })668669 it('can skip initial hydration', async () => {670 const storage = {test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 671–677why, one step back671 getItem: async (name: string) => {672 await sleep(10)673 return {674 state: { count: 42, name },675 version: 0,676 }677 },chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 678–702why, one step back678 setItem: () => {},679 removeItem: () => {},680 }681682 const onRehydrateStorageSpy = vi.fn()683 const useBoundStore = create(684 persist(685 () => ({686 count: 0,687 name: 'empty',688 }),689 {690 name: 'test-storage',691 storage: storage,692 onRehydrateStorage: () => onRehydrateStorageSpy,693 skipHydration: true,694 },695 ),696 )697698 expect(useBoundStore.getState()).toEqual({699 count: 0,700 name: 'empty',701 })702test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
line 703why, one step back703 // Asserting store hasn't hydratedchore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 704–705why, one step back704 expect(useBoundStore.persist.hasHydrated()).toBe(false)705test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 706–708why, one step back706 const rehydratePromise = useBoundStore.persist.rehydrate()707 await act(() => vi.advanceTimersByTimeAsync(10))708 await rehydratePromisechore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 709–713why, one step back709710 expect(useBoundStore.getState()).toEqual({711 count: 42,712 name: 'test-storage',713 })test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
line 714why, one step back714 expect(onRehydrateStorageSpy).toHaveBeenCalledWith(chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 715–721why, one step back715 { count: 42, name: 'test-storage' },716 undefined,717 )718 })719720 it('handles state updates during onRehydrateStorage', async () => {721 const storage = {test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 722–725why, one step back722 getItem: async () => {723 await sleep(10)724 return JSON.stringify({ state: { count: 1 } })725 },chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 726–754why, one step back726 setItem: () => {},727 removeItem: () => {},728 }729730 const useBoundStore = create<{ count: number; inc: () => void }>()(731 persist(732 (set) => ({733 count: 0,734 inc: () => set((s) => ({ count: s.count + 1 })),735 }),736 {737 name: 'test-storage',738 storage: createJSONStorage(() => storage),739 onRehydrateStorage: () => (s) => s?.inc(),740 },741 ),742 )743744 function Counter() {745 const { count } = useBoundStore()746 return <div>count: {count}</div>747 }748749 render(750 <StrictMode>751 <Counter />752 </StrictMode>,753 )754test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 755–756why, one step back755 await act(() => vi.advanceTimersByTimeAsync(10))756 expect(screen.getByText('count: 2')).toBeInTheDocument()chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 757–759why, one step back757 expect(useBoundStore.getState().count).toEqual(2)758 })759fix(persist): use latest state in post-rehydration callback (#3391)Shohjahonbefore adoption6213fc1
lines 760–813why, one step back760 it('passes latest state to post-rehydration callback after hydration-triggered updates', async () => {761 const onRehydrateStorageSpy = vi.fn()762 const storage = {763 getItem: async () => {764 await sleep(10)765 return JSON.stringify({766 state: { count: 1, bumped: false },767 version: 0,768 })769 },770 setItem: () => {},771 removeItem: () => {},772 }773774 const useBoundStore = create(775 persist(() => ({ count: 0, bumped: false }), {776 name: 'test-storage',777 storage: createJSONStorage(() => storage),778 onRehydrateStorage: () => onRehydrateStorageSpy,779 }),780 )781782 let patchedDuringHydration = false783 const unsubscribe = useBoundStore.subscribe((state) => {784 if (!patchedDuringHydration && state.count === 1 && !state.bumped) {785 patchedDuringHydration = true786 useBoundStore.setState({ bumped: true })787 }788 })789790 function Counter() {791 const { count, bumped } = useBoundStore()792 return (793 <div>794 count: {count}, bumped: {String(bumped)}795 </div>796 )797 }798799 render(800 <StrictMode>801 <Counter />802 </StrictMode>,803 )804805 await act(() => vi.advanceTimersByTimeAsync(10))806 expect(screen.getByText('count: 1, bumped: true')).toBeInTheDocument()807 expect(onRehydrateStorageSpy).toHaveBeenCalledWith(808 { count: 1, bumped: true },809 undefined,810 )811 unsubscribe()812 })813chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 814–816why, one step back814 it('can rehydrate state with custom deserialized Map', async () => {815 const onRehydrateStorageSpy = vi.fn()816 const storage = {test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 817–819why, one step back817 getItem: async () => {818 await sleep(10)819 return JSON.stringify({chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 820–822why, one step back820 state: {821 map: { type: 'Map', value: [['foo', 'bar']] },822 },test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 823–824why, one step back823 })824 },chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 825–852why, one step back825 setItem: () => {},826 removeItem: () => {},827 }828829 const useBoundStore = create(830 persist(831 () => ({832 map: new Map(),833 }),834 {835 name: 'test-storage',836 storage: createJSONStorage(() => storage, { replacer, reviver }),837 onRehydrateStorage: () => onRehydrateStorageSpy,838 },839 ),840 )841842 function MapDisplay() {843 const { map } = useBoundStore()844 return <div>map: {map.get('foo')}</div>845 }846847 render(848 <StrictMode>849 <MapDisplay />850 </StrictMode>,851 )852test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 853–855why, one step back853 await act(() => vi.advanceTimersByTimeAsync(10))854 expect(screen.getByText('map: bar')).toBeInTheDocument()855 expect(onRehydrateStorageSpy).toHaveBeenCalledWith(chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 856–890why, one step back856 { map: new Map([['foo', 'bar']]) },857 undefined,858 )859 })860861 it('can persist state with custom serialization of Map', async () => {862 const { storage, setItemSpy } = createPersistantStore(null)863 const map = new Map()864865 const createStore = () => {866 const onRehydrateStorageSpy = vi.fn()867 const useBoundStore = create(868 persist(() => ({ map }), {869 name: 'test-storage',870 storage: createJSONStorage(() => storage, { replacer, reviver }),871 onRehydrateStorage: () => onRehydrateStorageSpy,872 }),873 )874 return { useBoundStore, onRehydrateStorageSpy }875 }876877 // Initialize from empty storage878 const { useBoundStore, onRehydrateStorageSpy } = createStore()879880 function MapDisplay() {881 const { map } = useBoundStore()882 return <div>map-content: {map.get('foo')}</div>883 }884885 render(886 <StrictMode>887 <MapDisplay />888 </StrictMode>,889 )890test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 891–893why, one step back891 expect(screen.getByText('map-content:')).toBeInTheDocument()892 await act(() => vi.advanceTimersByTimeAsync(10))893 expect(onRehydrateStorageSpy).toHaveBeenCalledWith({ map }, undefined)chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 894–896why, one step back894895 // Write something to the store896 const updatedMap = new Map(map).set('foo', 'bar')feat(middleare/persist): return storage promise from setState (#3206)Daishi Katobefore adoptionfeddc0c
lines 897–899why, one step back897 act(() => {898 useBoundStore.setState({ map: updatedMap })899 })test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
line 900why, one step back900 expect(screen.getByText('map-content: bar')).toBeInTheDocument()chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
line 901why, one step back901test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
line 902why, one step back902 expect(setItemSpy).toHaveBeenCalledWith(chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 903–917why, one step back903 'test-storage',904 JSON.stringify({905 state: { map: { type: 'Map', value: [['foo', 'bar']] } },906 version: 0,907 }),908 )909910 // Create the same store a second time and check if the persisted state911 // is loaded correctly912 const {913 useBoundStore: useBoundStore2,914 onRehydrateStorageSpy: onRehydrateStorageSpy2,915 } = createStore()916 function MapDisplay2() {917 const { map } = useBoundStore2()test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
line 918why, one step back918 return <div>map-content2: {map.get('foo')}</div>chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
lines 919–926why, one step back919 }920921 render(922 <StrictMode>923 <MapDisplay2 />924 </StrictMode>,925 )926test: migrate 'findByText' and 'waitFor' to fake timers with 'getByText' (#3324)Wonsuk Choibefore adoption376af78
lines 927–932why, one step back927 await act(() => vi.advanceTimersByTimeAsync(10))928 expect(screen.getByText('map-content2: bar')).toBeInTheDocument()929 expect(onRehydrateStorageSpy2).toHaveBeenCalledWith(930 { map: updatedMap },931 undefined,932 )chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
line 933why, one step back933 })fix(persist): prevent race condition during concurrent rehydrate calls (#3336)Niyazbefore adoptiond0cb549
lines 934–1064why, one step back934935 it('should handle multiple concurrent rehydrate calls (only last one wins)', async () => {936 let callCount = 0937 const storage = {938 getItem: async () => {939 const currentCall = ++callCount940 await sleep(10)941 return JSON.stringify({942 state: { count: currentCall * 10 },943 version: 0,944 })945 },946 setItem: () => {},947 removeItem: () => {},948 }949950 const onFinishHydrationSpy = vi.fn()951 const useBoundStore = create(952 persist(() => ({ count: 0 }), {953 name: 'test-storage',954 storage: createJSONStorage(() => storage),955 skipHydration: true,956 }),957 )958959 useBoundStore.persist.onFinishHydration(onFinishHydrationSpy)960961 // Start first rehydration962 const promise1 = useBoundStore.persist.rehydrate()963 // Immediately start second rehydration (before first completes)964 const promise2 = useBoundStore.persist.rehydrate()965 // Start third rehydration966 const promise3 = useBoundStore.persist.rehydrate()967968 // Advance time to complete all hydrations969 await act(() => vi.advanceTimersByTimeAsync(30))970 await Promise.all([promise1, promise2, promise3])971972 // Only the last rehydration should have applied its state973 // callCount will be 3, so count should be 30974 expect(useBoundStore.getState().count).toBe(30)975976 // onFinishHydration should only be called once (for the last hydration)977 expect(onFinishHydrationSpy).toHaveBeenCalledTimes(1)978 expect(onFinishHydrationSpy).toHaveBeenCalledWith({ count: 30 })979 })980981 it('should not overwrite user state changes made during async hydration', async () => {982 const storage = {983 getItem: async () => {984 await sleep(20)985 return JSON.stringify({986 state: { count: 42, userValue: 'from-storage' },987 version: 0,988 })989 },990 setItem: () => {},991 removeItem: () => {},992 }993994 const useBoundStore = create(995 persist(() => ({ count: 0, userValue: 'initial' }), {996 name: 'test-storage',997 storage: createJSONStorage(() => storage),998 // Custom merge that preserves user changes made during hydration999 merge: (persistedState, currentState) => ({1000 ...currentState,1001 ...(persistedState as object),1002 }),1003 }),1004 )10051006 // User makes a change while hydration is in progress1007 await act(() => vi.advanceTimersByTimeAsync(10))1008 useBoundStore.setState({ count: 100 })10091010 // Complete hydration1011 await act(() => vi.advanceTimersByTimeAsync(10))10121013 // The merge function combines storage state with current state1014 // Storage has count: 42, userValue: 'from-storage'1015 // Current state before merge has count: 100, userValue: 'initial'1016 // After merge (storage overwrites): count: 42, userValue: 'from-storage'1017 expect(useBoundStore.getState()).toEqual({1018 count: 42,1019 userValue: 'from-storage',1020 })1021 })10221023 it('should abort hydration with async migration when newer hydration starts', async () => {1024 let migrationCount = 01025 const storage = {1026 getItem: async () => {1027 await sleep(5)1028 return JSON.stringify({1029 state: { count: 1 },1030 version: 0,1031 })1032 },1033 setItem: () => {},1034 removeItem: () => {},1035 }10361037 const useBoundStore = create(1038 persist(() => ({ count: 0 }), {1039 name: 'test-storage',1040 storage: createJSONStorage(() => storage),1041 version: 1,1042 migrate: async (state) => {1043 migrationCount++1044 await sleep(10)1045 return { count: (state as { count: number }).count * 10 }1046 },1047 skipHydration: true,1048 }),1049 )10501051 // Start first rehydration (will trigger migration)1052 useBoundStore.persist.rehydrate()1053 await act(() => vi.advanceTimersByTimeAsync(5)) // getItem completes10541055 // Start second rehydration before migration completes1056 useBoundStore.persist.rehydrate()10571058 // Advance time to complete everything1059 await act(() => vi.advanceTimersByTimeAsync(20))10601061 // Both hydrations triggered migration, but only last one should apply1062 expect(migrationCount).toBe(2)1063 // Final state should be from second hydration's migration1064 expect(useBoundStore.getState().count).toBe(10)fix(persist): clearStorage() should invalidate concurrent async rehydration (#3555)Copilotbefore adoption3febf8c
lines 1065–1242why, one step back1065 })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 })fix(persist): prevent race condition during concurrent rehydrate calls (#3336)Niyazbefore adoptiond0cb549
line 1243why, one step back1243 })chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f
line 1244why, one step back1244})