Skip to content

Commit

Permalink
fix(vanilla): unexpected null state update behavior (#2213)
Browse files Browse the repository at this point in the history
* fix: unexpected null state update behavior

* chore: lint code

* test: add test for setting state to null

---------

Co-authored-by: wulimao <tao@trlab.com>
  • Loading branch information
wulimao49 and wulimao authored Nov 27, 2023
1 parent f5561df commit 949b505
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/vanilla.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ const createStoreImpl: CreateStoreImpl = (createState) => {
if (!Object.is(nextState, state)) {
const previousState = state
state =
replace ?? typeof nextState !== 'object'
replace ?? (typeof nextState !== 'object' || nextState === null)
? (nextState as TState)
: Object.assign({}, state, nextState)
listeners.forEach((listener) => listener(state, previousState))
Expand Down
18 changes: 18 additions & 0 deletions tests/vanilla/basic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,24 @@ it('can set the store without merging', () => {
expect(getState()).toEqual({ b: 2 })
})

it('can set the object store to null', () => {
const { setState, getState } = createStore<{ a: number } | null>(() => ({
a: 1,
}))

setState(null)

expect(getState()).toEqual(null)
})

it('can set the non-object store to null', () => {
const { setState, getState } = createStore<string | null>(() => 'value')

setState(null)

expect(getState()).toEqual(null)
})

it('works with non-object state', () => {
const store = createStore<number>(() => 1)
const inc = () => store.setState((c) => c + 1)
Expand Down

1 comment on commit 949b505

@vercel
Copy link

@vercel vercel bot commented on 949b505 Nov 27, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.