For example, we have a state defined like this which is having some todos and we want to change done of that todo if they are completed
this.state = {
// store an array of todo objects
todos: [
{ task: 'do the dishes', done: false, id: 1 },
{ task: 'vacuum the floor', done: true, id: 2 }
]
};
For that, we can do this away.
const theTodo = this.state.todos.find(t => t.id === id);
theTodo.done = true; // NOOOOO
this.setState({
todos: this.state.todos
});
}
But I am a little confused that find method on the array will return us the element which matches the condition inside it and we store it in a different variable and then access done to change it to true. But still, we haven't changed the original state value as this was a copy one.
Then how come we can use this to save it?
this.setState({
todos: this.state.todos // bad
});