score:2

Accepted answer

Instead of destructuring the array and using map, I typically update a single item's value with a single map that replaces the item I am updating and returns the existing value for all other items. Something like this:

this.setState((prevState) => {
  return {
    todoList: prevState.todoList.map((task) => {
      if (task.id === key) {
        return { ...task, completed: true };
      } else {
        return task;
      }
    }),
  };
});

Also, notice that this example passes a function to this.setState rather than an object. If you are updating the state based on the previous state (in this example using todoList from the previous state) you should use the function method. setState is asynchronous and you could get unexpected results from using this.state to compute the new state.


Related Query

More Query from same tag