From c14a4e590a5e9d3a92d6e21b4f81d0f64c627dd8 Mon Sep 17 00:00:00 2001 From: Jason Quense Date: Thu, 28 Mar 2019 11:11:42 -0400 Subject: [PATCH] feat: allow return null from useMergeState updater function --- src/useMergeState.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/useMergeState.ts b/src/useMergeState.ts index e06e790..eff7705 100644 --- a/src/useMergeState.ts +++ b/src/useMergeState.ts @@ -1,12 +1,12 @@ import { useState } from 'react' -type Updater = (state: TState) => Partial +type Updater = (state: TState) => Partial | null export type MergeStateSetter = ( update: Updater | Partial | null ) => void -export default function useMergeState( +export default function useMergeState( initialState: TState ): [TState, MergeStateSetter] { const [state, setState] = useState(initialState) @@ -14,7 +14,10 @@ export default function useMergeState( const updater = (update: Updater | Partial | null) => { if (update === null) return if (typeof update === 'function') - setState(state => ({ ...state, ...update(state) })) + setState(state => { + const nextState = update(state) + return nextState == null ? state : { ...state, ...nextState } + }) setState(state => ({ ...state, ...update })) }