0

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?

Luciano M.
  • 3
  • 1
  • 3
  • 1
    The problem is that the interval callback has the `checkAnswer` that was in scope when the interval callback was created, and `checkAnswer` has the `count` that was in scope when that `checkAnswer` was created, but when you call `setCounter`, it makes React call your component function again, creating an entirely new `count` (with the updated value), `checkAnswer`, and everything else in the component function. When the countdown is complete, the interval handler still has the old `checkAnswer`, with its old `count`. To fix it, at minimum `checkAnswer` shouldn't use... – T.J. Crowder Oct 26 '21 at 09:45
  • 1
    ...`count`, it should use `setCount` passing in a callback because the callback will get the up-to-date `count` value. But the above is fundamentally not how you'd do this in React. With React, you almost never do direct DOM manipulation; instead, you update state, and let React update the DOM. – T.J. Crowder Oct 26 '21 at 09:46
  • (The code shown also has syntax errors, there's at least a missing `}` on `const countDown =`. You have a `result` variable you never used [which isn't a syntax error], and a `resultat` variable that you never declare [which is a runtime error if you're using strict mode, which I'd recommend], ...) – T.J. Crowder Oct 26 '21 at 09:49

0 Answers0