Skip to content

Commit

Permalink
feat: allow return null from useMergeState updater function
Browse files Browse the repository at this point in the history
  • Loading branch information
jquense committed Mar 28, 2019
1 parent 5b749b6 commit c14a4e5
Showing 1 changed file with 6 additions and 3 deletions.
9 changes: 6 additions & 3 deletions src/useMergeState.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
import { useState } from 'react'

type Updater<TState> = (state: TState) => Partial<TState>
type Updater<TState> = (state: TState) => Partial<TState> | null

export type MergeStateSetter<TState> = (
update: Updater<TState> | Partial<TState> | null
) => void

export default function useMergeState<TState>(
export default function useMergeState<TState extends {}>(
initialState: TState
): [TState, MergeStateSetter<TState>] {
const [state, setState] = useState<TState>(initialState)

const updater = (update: Updater<TState> | Partial<TState> | 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 }))
}
Expand Down

0 comments on commit c14a4e5

Please sign in to comment.