I’m currently learning React by creating a CRUD app and am trying useState() (haven’t started looking into useEffect() or any other hooks yet). My app is a TODO list, and I want to create items with running IDs.
I have the following code:
const initialList = [
{ id: 0, title: 'Buy milk' },
];
const [list, setList] = useState(initialList);
function addTask() {
var textInTextbox = document.getElementById('input-textbox').value;
let nextId = 1;
setList([...list,
{
id: nextId++,
title: textInTextbox,
}
]);
}
return (
<>
<label for="item">Type item here: </label>
<input type='text' id="input-textbox"></input>
<div>
<button onClick={() => addTask()}>Add task</button>
{list.map(item => {
return (
<div>
{item.id} : {item.title}
</div>
)
})}
</div>
</>
)
When I add a task, the item title displays correctly, but the ID always remain as 1 and isn’t running. Please guide me in the correct direction. Thanks!