Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

113
Views
Onclick event push new item into array but the item is only pushed on the next click

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)
  }
}
about 4 years ago · Santiago Gelvez
1 answers
Answer question

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)
  }
}
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!