Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: delete root keys with immer middleware #2481

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 3 additions & 6 deletions src/middleware/immer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ type StoreImmer<S> = S extends {
? {
setState(
nextStateOrUpdater: T | Partial<T> | ((state: Draft<T>) => void),
dbritto-dev marked this conversation as resolved.
Show resolved Hide resolved
shouldReplace?: boolean | undefined,
...a: SkipTwo<A>
): Sr
}
Expand All @@ -56,12 +55,10 @@ type ImmerImpl = <T>(
const immerImpl: ImmerImpl = (initializer) => (set, get, store) => {
type T = ReturnType<typeof initializer>

store.setState = (updater, replace, ...a) => {
const nextState = (
typeof updater === 'function' ? produce(updater as any) : updater
) as ((s: T) => T) | T | Partial<T>
store.setState = (updater, _, ...a) => {
const nextState = produce(updater as any) as (s: T) => T

return set(nextState as any, replace, ...a)
return set(nextState as any, /* replace */ true, ...a)
}

return initializer(store.setState, get, store)
Expand Down
48 changes: 48 additions & 0 deletions tests/immerMiddleware.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { describe, expect, it } from 'vitest'
import { create } from 'zustand'
import { immer } from 'zustand/middleware/immer'
import { createStore } from 'zustand/vanilla'

describe('immer middleware', () => {
it('typical case', () => {
type CounterState = {
count: number
inc: () => void
}

const useBoundStore = create<CounterState>()(
immer((set, get) => ({
count: 0,
inc: () =>
set((state) => {
state.count = get().count + 1
}),
})),
)

expect(useBoundStore.getState().count).toEqual(0)

useBoundStore.getState().inc()

expect(useBoundStore.getState().count).toEqual(1)
})

// Bug: https://github.com/pmndrs/zustand/discussions/2480
it('delete key at root of state', () => {
type State = Record<string, any>

const store = createStore<State>()(immer(() => ({})))

expect(store.getState()).toEqual({})

store.setState((state) => {
state.x = 3
})

expect(store.getState()).toEqual({ x: 3 })
store.setState((state) => {
delete state.x
})
expect(store.getState()).toEqual({})
})
})