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)