Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

115
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda