I want to understand why the code can not work by copying the array from the state. checkboxes is an array of Booleans. I was of the opinion that if I assign checkboxes from state directly to tempCheckboxes it will be an alias and modifying an alias will indirectly impact state variable. But that is not the case. And I want to know why? Thanks for your help.
checkRow = (index, checked) => {
let tempCheckboxes = this.state.checkboxes.slice();
let all = true;
tempCheckboxes[index] = checked;
all = tempCheckboxes.every((isChecked) => this.isTrue(isChecked));
this.setState((prevState) => ({ ...prevState, checkboxes: tempCheckboxes, checkAll: all }));
};
Above code fails to work but following code works
checkRow = (index, checked) => {
let tempCheckboxes = this.state.checkboxes
let all = true;
tempCheckboxes[index] = checked;
all = tempCheckboxes.every((isChecked) => this.isTrue(isChecked));
this.setState((prevState) => ({ ...prevState, checkboxes: tempCheckboxes, checkAll: all }));
};
Edit : Reason for this question is in react we should not directly change the state with assignment but instead use setState to do so. In my opinion 2nd version of code is doing it. Earlier title for the question was not precise so changed it.