Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

116
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda