The following code displays a list of items. The list is held in a state variable list. There are two ways to add items to the list: either manually by clicking the Inc button, or by starting the timer which adds an item to the list every 1 second.
The Inc button works but the timer function does not. When examining the timer function, the state variable list does not appear to persist its new length between calls.
Why is this? Thank you for reading.
import React, { useState } from 'react';
export function Tester() {
const [list, setList] = useState([]);
var timer = null;
function startTimer() {
// Start a timer
if (timer == null)
timer = setTimeout(timeoutCallback, 1000);
}
function timeoutCallback() {
//
timer = null;
//
btnClicked();
//
startTimer();
}
function btnClicked() {
let today = new Date();
let strTime = today.getHours() + ':' + today.getMinutes() + ':' + today.getSeconds();
setList([
...list,
{
name: "item " + strTime,
id: list.length + 1
}
]);
}
const renderedItems = list.map(
X => {
return <span key={X.id}>{X.id}+{X.name} </span>
}
);
return (
<>TESTER
<button onClick={startTimer}>Timer</button>
<button onClick={btnClicked}>Inc</button>
{renderedItems}
</>
);
}