The updater function returned from the useState
hook (setTodoList
in your case) can be used with either of the following:
- a value (for example,
setTodoList([])
to set it to an empty array)
- a callback that returns a value.
The callback takes a single prevState
argument which is just the previous state value. The callback should then return a new state value.
This works great for array state variables since you will usually want to add/change/remove one item from the array.
Here's something you could try:
function changeItem (itemId, newItem) {
setTodoList(function (oldTodoList) {
// create a new array without the item where item.todoId == itemId
const itemsWithoutNewId = oldTodoList.filter((item) => item.id !== id);
// add the new item and this array together and put it in another array
const itemsWithNew = [...itemsWithoutNewId, newItem];
// Return the final array
return itemsWithNew;
});
}
or as a one-liner (functionally equivalent):
const changeItem = (id, newItem) => setTodoList(oldTodoList => [...oldTodoList.filter(item => item.todoId !== id), newItemForId]);
They can both be used like this:
const item = {
todoId: 1,
todoName: "New Todo",
todo: []
};
changeItem(1, item);
console.log(todoList);
/*
[
{
todoId: 0,
todoName: "Personal",
todo: []
},
{
todoId: 1,
todoName: "New Todo",
todo: []
},
{
todoId: 2,
todoName: "College",
todo: []
},
]
*/