Why use immer for this function?

324 Views Asked by At

ToggleAttached function inside CauseSpecificPage.js. This function toggles the follow/following button on the cause specific page: st-bnv.

What is the benefit of using Immer in this situation? Do we even need to use Immer?

 const ToggleAttached = () => {
if (state.isDisabled) {
  return
}

const oldValue = state.isAttached
setState(produce((draftState) => {
  draftState.isDisabled = true
  draftState.isAttached = !oldValue
}))
ToggleFollow({ causeId })
  .then(response => {
    setState(produce((draftState) => {
      draftState.isAttached = response.data.isAttached
    }))
  })
  .catch(error => {
    setState(produce((draftState) => {
      draftState.isAttached = oldValue
    }))
    HandleError(error)
  })
  .finally(() => setState(produce((draftState) => {
    draftState.isDisabled = false
  })))}
1

There are 1 best solutions below

0
On

Immer is a little more verbose but is more maintainable in the long run. Immer was created to help us to have an immutable state, it’s a library created based on the “copy-on-write” mechanism — a technique used to implement a copy operation in on modifiable resources. We can see that the concept of immutability is getting used more and becoming more common in the React community. But to make sure that we’re doing it the right way, we can use Immer for the job. Immer adds more benefits on redux states.