Fix Cannot Assign To Read Only Property Error In LWC In Lightning web components
Example Problem Code:
allCheckBoxChange(event) {
for (let j = 0; j < this.allOppList.length; j++) {
this.allOppList[j].isChecked = event.detail.checked;
}
}
In above code "allOppList" is the data of wired property. When allCheckBoxChange() fynction gets invoked we will get below error Uncaught TypeError: Cannot assign to read only property '0' of object '[object Array]'
Solution Code:
allCheckBoxChange(event) {
let tempAllRecords = Object.assign([], this.allOppList);
for (let j = 0; j < this.allOppList.length; j++) {
let tempRec = Object.assign({}, tempAllRecords[j]);
tempRec.isChecked = event.detail.checked;
tempAllRecords[j] = tempRec;
}
this.allOppList = tempAllRecords;
}
In above code we are cloning wired property "allOppList" to new temporary variable tempAllRecords and after update, assigning temporary list to allOppList. In for loop we are updating every record of allOppList, so we are cloning every record and updating the cloned record and assigning back to actual record. So that we can avoid read only property issue.
Note: Object.assign() function is the one of cloning method in JavaScript.
No Comment to " How To Fix Cannot Assign To Read Only Property Error In LWC-Lighting Web Components "