in React app I'm trying to increment +1 to the id field of each object in the array.
function App() {
const[todos, setTodos] = useState([
{
id: 1,
title: 'Take out the trash',
completed: false
},
{
id: 2,
title: 'Dinner',
completed: false
},
{
id: 3,
title: 'Meeting with boss',
completed: false
}
]);
function onClick(){
setTodos(todos => todos.map(todo => todo.id = todo.id + 1))
}
return (
<div className="App">
<div className="todo-list">
<ul>
{todos.map(todo => <li>{todo.id},{todo.title},{String(todo.completed)}</li>)}
</ul>
<button onClick={()=>onClick()}
>Update
</button>
</div>
</div>
);
}
On the initial rendering of the page list of objects is displayed properly. On first click of the button they change to this:
,,undefined
,,undefined
,,undefined
On 3rd click to this error:
TypeError: Cannot create property 'id' on number '2'
did I miss something about the map function ?