简体   繁体   中英

How to create a custom hook, that works like setState in a class component in React with Typescript

I'm trying to create a custom hook, that updates the state, instead of replacing the state, the same, as setState in class components does. It should work like this:

part of the render:

interface IExample {
  foo: number
  bar: string
}

const [state, setState] useCustomHook<IExample>({foo: 1, bar: 'aaa'})

in some callback:

setState({bar: 'bbb'}) // after everything settles, the state should be: {foo: 1, bar: 'bbb'}

Attempted solution (corrected, works now):

const isFunction = (value: any): value is Function => typeof value === 'function'

export default <T>(initialState: T | (() => T)):[T, (newState: Partial<T> | ((prevState: Partial<T>) => Partial<T>)) => void] => {
  const [state, setState] = useState<Partial<T>>(initialState)

  const setStateMerging = (newState: Partial<T> | ((prevState: Partial<T>) => Partial<T>)) => {
    if (isFunction(newState)) {
      setState((prevState) => ({ ...prevState, ...newState(prevState) }))
    } else {
      setState((prevState) => ({ ...prevState, ...newState }))
    }
  }

  return [state, setStateMerging]
}

Here is a demo

The problem is corrected after @Jonas Wilms answer.

你的isFunction需要是一个打字员:

 const isFunction = (value: any): value is Function => typeof value === 'function'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM