As a beginner to React, I am trying to build a stopwatch.
While the variables (numbers) displayed at screen are correct, trying to access said variables with a 'console.log()' or if-statement, it only reads the old value of that variable and not the actual one, displayed at the screen.
It very likely has a very simple solution, but I really could not find a solution per web or AI.
This is my used code, shortened, but still working:
import React, { useState } from 'react';
export default function Anzeige() {
const [time, setTime] = useState({
dezisec: 0
});
const Erhohen = () => {
console.log(time)
setTime((prevTime) => ({
...prevTime,
dezisec: prevTime.dezisec+1
}))
console.log(time)
logging()
}
const logging = () => {
console.log(time)
}
const startTimer = () => {
const t = setInterval(Erhohen, 1000)
}
return (
<p onClick={startTimer}>{time.dezisec}</p>
)
}
Explanation:
When clicking on the p
element, "dezisec" increases by 1 on the display/screen. But unexpectedly, both "console.log(time)" print out "dezisec: 0" the whole time. The same goes for the "logging()" function.
I already looked through possible solutions, but they seemed all to just change the location of the "console.log()" or used a function outside the "setTime", like the "logging()" function I used.