0

I'm a bit of a rookie to react I was wondering why this happens: I have a toggle activate button which toggles the selected item activation

const handleToggleActivation = async () => {
    ...
    setData((prev) => {
      const newState = [...prev]
      newState[selectedRow.index].isActive = !prev[selectedRow.index].isActive;
      return newState;
    })
    ...

Somewhy this piece of code won't work unless I make the change in the code below (which is saving the current state of isActive outside the setData) otherwise the new state will be exactly the same as the previous state (isActive value doesn't toggle)

const handleToggleActivation = async () => {
    ...
    let isActive = data[selectedRow.index].isActive
    setData((prev) => {
      const newState = [...prev]
      newState[selectedRow.index].isActive = !isActive;
      return newState;
    })
    ...

Any ideas why this happens?

SandStone
  • 161
  • 1
  • 7
  • What are `data` and `selectedRow.index`? How do you conclude that the state doesn't change, where do you use it? What result do you get when you log `!prev[selectedRow.index].isActive` in the callback? – Bergi Aug 28 '22 at 18:26
  • 1
    A clear problem is that you're mutating the objects in your state, instead of creating a new immutable state. You only make a copy of the `prev` array, but no copy of the `prev[selectedRow.index]` object whose `.isActive` property you reassign. (It's weird though that your workaround would solve this problem) – Bergi Aug 28 '22 at 18:27

1 Answers1

-2

This is happening because React useState is async. have you seen this The useState set method is not reflecting a change immediately?. This may be helpful for your question and will clear your doubts

  • It's not the state change isn't reflected, it's that the state doesn't change at all in the situation mentioned above. – SandStone Aug 28 '22 at 13:34