• How To Fix Cannot Assign To Read Only Property Error In LWC-Lighting Web Components

    Published By: salesforcepoint
    Published: Sunday, 2 August 2020
    A- A+

    Fix Cannot Assign To Read Only Property Error In LWC In Lightning web components 

    How To Fix Cannot Assign To Read Only Property Error In Lightning Web Components

    If we are trying to update public (@api) property or wired property in JavaScript function we usually get this issue. For resolving this issue, we need to clone that property to new variable and update it. After updating assign temporary variable to actual property.

     Example Problem Code:
     allCheckBoxChange(event) {
            for (let j = 0; j < this.allOppList.length; j++) {
                this.allOppList.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 "