-1
export default function Raffle(){
/*......*/

  setCandidates(() => {
    candidates.splice(winnerIdx,1) //(*)
    return [...candidates];
    })
  }

}

at (*) line, setCandidates Function remove 2 candidates. but below is run as expected.

    setCandidates(() => {
      let remain = [...candidates];
      remain.splice(winnerIdx,1);
      return [...remain];
    })

I don't know why the splice method activate twice in first case.

what happened when i modified state in setState function?

ion loi
  • 1
  • 4
  • 2
    Does this answer your question? [Why does calling react setState method not mutate the state immediately?](https://stackoverflow.com/questions/30782948/why-does-calling-react-setstate-method-not-mutate-the-state-immediately) – Samathingamajig Aug 02 '22 at 05:20

1 Answers1

0

You should provide a callback to your set state call, and then copy the argument, not mutate it. Mutating state is generally not good.

setCandidates((oldCandidates) => {
      let remain = [...oldCandidates];
      remain.splice(winnerIdx,1);
      return [...remain];
})

I'm not sure why exactly you were having the problem you were having, but dealing with state this way is much safer and will avoid any weird behavior.

Nathan
  • 73,987
  • 14
  • 40
  • 69