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

106
Visualizações
useState Hook does not pass to other functions

In my component i have a Button which increases the counter useState hook.

const Component = () => {
  const [count, setCount] = useState(0)

  let cd = 5
  let result = 25

  const counterHandler = () => {
    document.getElementById('count').innerHTML = count
    setCount(count + 1)
  }

  const countDown = () => {    
    let interval = setInterval(() => {
      if (cd > 0) {
        cd -= 1
        document.getElementById('countDown').innerHTML = cd
      } else if (cd === 0) {
        checkAnswer()
        clearInterval(interval)
      }
   }, 1000)
 
   const checkAnswer = () => {
     if (count > resultat) {
       document.getElementById('message').innerHTML = 'Yess!'
     } else {
       document.getElementById('message').innerHTML = 'Wrong!!'
       setTimeout(() => {
         document.getElementById('message').innerHTML = ''
       }, 2000)
     }
   }

  return (
    <div>
      <h1 id='count'>
        {count}
      </h1>
      <h4 id='countDown'>
        0
      </h4>
      <button onClick={counterHandler}>Push Me!</button>
      <button id='go-btn' onClick={countdown}>Go</button>
      <h4 id='message'>
      </h4>  
    </div>
  )
}

After a countdown the count is checked if it's the same as in the result const. However, if I log the count in the checkAnswer function, it shows always a count of 0. Therefor the result is always wrong, no matter how many times the counterHandler- button get pressed. What am I doing wrong?

about 4 years ago · Juan Pablo Isaza
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