From 949b505a4b5414d5b249c413e9847bb0df559a42 Mon Sep 17 00:00:00 2001 From: wulimao49 <73568161+wulimao49@users.noreply.github.com> Date: Mon, 27 Nov 2023 17:35:14 +0800 Subject: [PATCH] fix(vanilla): unexpected null state update behavior (#2213) * fix: unexpected null state update behavior * chore: lint code * test: add test for setting state to null --------- Co-authored-by: wulimao --- src/vanilla.ts | 2 +- tests/vanilla/basic.test.ts | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/vanilla.ts b/src/vanilla.ts index ec9a5c07c9..d6366ced23 100644 --- a/src/vanilla.ts +++ b/src/vanilla.ts @@ -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)) diff --git a/tests/vanilla/basic.test.ts b/tests/vanilla/basic.test.ts index 99360376d5..9258db17d0 100644 --- a/tests/vanilla/basic.test.ts +++ b/tests/vanilla/basic.test.ts @@ -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(() => 'value') + + setState(null) + + expect(getState()).toEqual(null) +}) + it('works with non-object state', () => { const store = createStore(() => 1) const inc = () => store.setState((c) => c + 1)