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?