I have the following code in a React project:
changeChecked (task){
this.setState(prevState => {
let copy = [...prevState.tasks];
copy.forEach((item, index) => {
if (item == task) {
copy[index].checked = !copy[index].checked;
}
console.log(item);
// {name: "Task A", checked : true}
// {name: "Task B", checked : false}
});
console.log(copy);
// [
// {name : "Task A", checked : false},
// {name : "Task B", checked : false}
// ]
return {tasks : copy}
});
}
the initial state of the "this" (a React component) is this:
{
tasks : [
{name : "Task A", checked : false},
{name : "Task B", checked : false}
]
}
When I call that function (by button click) with the first task in the state.tasks as parameter, the forEach loop seems to change the item (see commented lines), but afterwards the "copy" array is unchanged. How so? When I execute this exact logic in an interactive javascript interpreter, the copy does have this first task changed.
EDIT: Now I see something very weird. When I expand the printed out object (line 8) in the console by clicking on it, I get this:
Console sais checked is true, but in the expanded view of the object it sais checked is false. What is going on here?