Skip to content
Myr

fix(middleware/persist): Merge storage value with the latest store state (#894)

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

* Merge storage value with the latest store state When using zustand store with Provider and Context, it's possible to mutate the store state in an useEffect callback before hydration creates `stateFromStorage`. It should merge the storage value with the latest store state instead of the config result since it can be out of date. * fix tests * Add test * commit

authored by zerofirework · committed by GitHub · parent 3acbb35 · Browse files · 2 files+57 added−1 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: Zero Liu <zerolxy@gmail.com>

Diff stats

2 files+57 added−1 removed

  • tests:+53 added−0 removed
  • other:+4 added−1 removed

2 files+57 added−1 removed

modified:src/middleware/persist.ts+4 added-1 removed
310 unmodified lines
311 }312 }313 })314 .then((migratedState) => {315 stateFromStorage = options.merge(migratedState as S, configResult)315 stateFromStorage = options.merge(316 migratedState as S,317 get() ?? configResult318 )319320 set(stateFromStorage as S, true)321 return setItem()322 })
46 unmodified lines
modified:tests/persistAsync.test.tsx+53 added
1import { useEffect } from 'react'2import { act, render, waitFor } from '@testing-library/react'3import create from 'zustand'4import { persist } from 'zustand/middleware'5
211 unmodified lines
217 )218 expect(onRehydrateStorageSpy).toBeCalledWith({ count: 99 }, undefined)219 })220221 it('can merge partial persisted state', async () => {222 const storage = {223 getItem: async () =>224 JSON.stringify({225 state: { count: 42 },226 }),227 setItem: () => {},228 removeItem: () => {},229 }230231 const useStore = create(232 persist(233 (set) => ({234 count: 0,235 name: 'unknown',236 setName: (name: string) => {237 set({ name })238 },239 }),240 {241 name: 'test-storage',242 getStorage: () => storage,243 }244 )245 )246247 function Component() {248 const { count, setName, name } = useStore()249 useEffect(() => {250 setName('test')251 }, [setName])252 return (253 <div>254 <div>count: {count}</div>255 <div>name: {name}</div>256 </div>257 )258 }259260 const { findByText } = render(<Component />)261262 await findByText('count: 42')263 await findByText('name: test')264265 expect(useStore.getState()).toEqual(266 expect.objectContaining({267 count: 42,268 name: 'test',269 })270 )271 })272273 it('can correclty handle a missing migrate function', async () => {274 console.error = jest.fn()275 const onRehydrateStorageSpy = jest.fn()276 const storage = {
237 unmodified lines