Fix Error “Cannot assign to read only property” and print Proxy Object of LWC

As its code-snippet post, its going to be very short but frequently used.

Salesforce decorator @track is reactive , which means if value in JavaScript changes, equivalent HTML UI would also change. You don’t need to mark primitive data types as track, as its enabled by default for them. However for complex structure / object we need to mark variable as @track.

Whenever any JavaScript object marked as @track, Salesforce wraps that object resulting in proxy object. If you try to print that on console, you would not be able to see its value.

That being said, there is no change in way you access it, it’s exactly like any other Javascript object we use. So, if you want to see content of proxy object, just call below method and pass your proxy object.

//Get Javascript object equivalent to Proxy
    proxyToObj(obj){
        return JSON.parse(JSON.stringify(obj));
    }

Another way is, just keep another variable without @track decorator to see content. However problem would be – you need to make sure to keep it in sync every time content of original @track object changes.

Fixing error – Cannot assign to read only property

Above error occurs when we try to change public property on LWC marked as @api

@api someVar
.... some code

somemethod(event){
    //error on below line - Cannot assign to read only property
     someVar.isSelected = true;
}

Above code block would throw an error as we are trying. to change property on object declared by @api

@api someVar
.... some code

somemethod(event){
    //clone @api variable using method we just created
    let tmpObj = this.proxyToObj(someVar);
     tmpObj.isSelected = true;
    //now assign this tmp variable back to original
   someVar = tmpObj;
}

To fix above error, use can do something like

Posted

in

by


Related Posts

Comments

One response to “Fix Error “Cannot assign to read only property” and print Proxy Object of LWC”

  1. Pulkit Malhotra Avatar
    Pulkit Malhotra

    I am getting error “this.this.proxyToObj()” is not a function

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Jitendra Zaa

Subscribe now to keep reading and get access to the full archive.

Continue Reading