Home > Software design >  Onclick event push new item into array but the item is only pushed on the next click
Onclick event push new item into array but the item is only pushed on the next click

Time:07-19

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)
  }
}

CodePudding user response:

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)
  }
}

CodePudding user response:

The useState React hook does not provide for a callback, unlike the class-based setState. Change:

setClickedArray(clickedArray => [...clickedArray,clicked])

to

setClickedArray([...clickedArray, clicked])
  • Related