I am learning react. When I click the reset timer button, instead of resetting the timer, a new second timer starts running concurrently. If I click the same button the third time, a new third timer starts at zero also running concurrently.
The same is happening when I click another button that says Jump 10 seconds. It's like its creating a new state instead of resetting the state.
Here is my app.jss code
function App() {
const [timeSpent, setTimeSpent] = useState(0);
setTimeout(() => setTimeSpent(timeSpent + 1),
1000
)
//Reset the timer
const resetTimer = () => setTimeSpent(0);
return (
<>
<Timer secondsPassed={timeSpent} />
<button onClick={resetTimer}>Reset Timer</button>
<button onClick={() => setTimeSpent(timeSpent +10)}>Jump 10 Seconds</button>
</>
);
}
export default App;
Here is my Timer.js code
function Timer({secondsPassed}) {
const formatting = () => {
if (secondsPassed < 60) {
return secondsPassed + ' Sec';
} else {
return Math.floor(secondsPassed/60) + ' Mins';
}
}
return (
<div>
<h3>Time Spent: {formatting()}</h3>
</div>
)
}