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 <tao@trlab.com>
This commit is contained in:
wulimao49 2023-11-27 17:35:14 +08:00 committed by GitHub
parent f5561dfb05
commit 949b505a4b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 19 additions and 1 deletions

View File

@ -73,7 +73,7 @@ const createStoreImpl: CreateStoreImpl = (createState) => {
if (!Object.is(nextState, state)) { if (!Object.is(nextState, state)) {
const previousState = state const previousState = state
state = state =
replace ?? typeof nextState !== 'object' replace ?? (typeof nextState !== 'object' || nextState === null)
? (nextState as TState) ? (nextState as TState)
: Object.assign({}, state, nextState) : Object.assign({}, state, nextState)
listeners.forEach((listener) => listener(state, previousState)) listeners.forEach((listener) => listener(state, previousState))

View File

@ -112,6 +112,24 @@ it('can set the store without merging', () => {
expect(getState()).toEqual({ b: 2 }) 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', () => { it('works with non-object state', () => {
const store = createStore<number>(() => 1) const store = createStore<number>(() => 1)
const inc = () => store.setState((c) => c + 1) const inc = () => store.setState((c) => c + 1)