[SalesForce] Uncaught TypeError: ‘set’ on proxy: trap returned falsish for property Name

Am not doing anything fancy, just trying to update a field on Contact in JS of LWC but getting this exception.

Uncaught TypeError: 'set' on proxy: trap returned falsish for property 'Name'
throws at mydomain/auraFW/javascript/mhontaYdOya4Y_lBu7v9yg/aura_prod.js:2:27687

HTML Code:

<template>

    <template if:true={wiredContact}>

        {wiredContact.Name}

        <lightning-input value={wiredContact.Name} onchange={updateName}></lightning-input>
    </template>

</template>

JS:

import { LightningElement ,wire,track,api } from 'lwc';
import myContact from "@salesforce/apex/ContactController.fetchContact";

export default class Myrefreshapextest extends LightningElement {


 @track wiredContact;

 @wire (myContact)
        fetchedContact({error, data}){
            if(data){
                console.log(JSON.stringify(data));
                this.wiredContact = data;
            }else if (error){
                console.log(error);
            }
    }

    updateName (event){
        console.log(JSON.stringify(event.detail.value));
        console.log(JSON.stringify(this.wiredContact));
        this.wiredContact.Name = event.detail.value;
    }

}

Apex:

public class ContactController {

    @AuraEnabled(cacheable=true)
    public static Contact fetchContact(){
        return [SELECT Id,Name FROM COntact LIMIT  1];
    }
}

On top of my head, am not doing anything wrong, anyone has idea what's wrong with my code?

When I print console.log(JSON.stringify(this.wiredContact)); I get old values so am pretty sure it exists.

I tried with @track and @api, but same response. Can anyone shed some light?

Best Answer

Cached items are set as read-only (because otherwise you could corrupt the cache). If you want a modifiable object, you need to clone it.

this.wiredContact = Object.assign({}, data);

Based on comments, you can also use the rest parameter syntax in LWC:

this.wiredContact = {...data};

If you don't care about some mobile browsers, and you're using Lightning Web Security instead of Locker Service, you can also use the structuredClone function, which can handle even recursive structures and other things that the JSON.parse(JSON.stringify(value)) trick doesn't support. You can check the status of structuredClone on Can I Use.

Related Topic