2 years ago

#74230

test-img

Alex Turpin

How to type a custom Immer update function?

I'm using Immer with React and I want to create a custom produce function that does something with the new state. I want to pass this produce function down to components so they can call it to update the state, and so that I can do something with the newly updated state. I can't seem to figure out how to type that function however.

It seems that ValidRecipeReturnType isn't exported. I was able to do it with use-immer's WriteFunction but use-immer doesn't return the new state after it's set.

const [state, setState] = useState<MyState>()

const updateState = useCallback((recipe) => {
  const newState = produce(state, recipe)
  // do something else with newState
  setState(updateState)
}, [state, setState])

How can I type the recipe param from updateState?

reactjs

typescript

immer.js

0 Answers

Your Answer

Accepted video resources