0

I am trying to push the new item, or setState in React, after a click on the target. I console.log the event.target and it returned what I expected. However, it is not added to the array immediately. Only after the next click, the array is updated, which means that, for example, after I clicked 10 times, the array only has 9 items in it without the last one I clicked. And then the 10th one would be added after I click again. Appreciate the help!

const [clickedArray, setClickedArray] = useState([])

const handleClick = (e) => {
  const clicked = e.target.alt
  console.log(clicked)
  setClickedArray(clickedArray => [...clickedArray,clicked])
  console.log(clickedArray)

  if(hasDuplicates(clickedArray)){
    alert('over')
    setScore(0)
    setClickedArray([])
    if(score > highScore){
      setHighScroe(score)
    }
  } else{
    setScore(clickedArray.length)
  }
}
Matthew Herbst
  • 29,477
  • 23
  • 85
  • 128
  • `clickedArray` is a `const`, it can't just change magically. React works asynchronously, the change will be present in the next render. – Konrad Jul 18 '22 at 20:35
  • Ah I see. Do you mind telling me the solution to this though? I am very new to react or programming in general. – Kevin Wang Jul 18 '22 at 20:40

1 Answers1

0

Not relying on the state that was just changed is the solution.

const [clickedArray, setClickedArray] = useState([])

const handleClick = (e) => {
  const clicked = e.target.alt
  const newArray = [...clickedArray,clicked]

  if(hasDuplicates(newArray)){
    alert('over')
    setScore(0)
    setClickedArray([])
    if(score > highScore){
      setHighScroe(score)
    }
  } else{
    setClickedArray(newArray)
    setScore(clickedArray.length)
  }
}
Konrad
  • 21,590
  • 4
  • 28
  • 64