Unable to Change attribute in JS Object passed from Parent as API Variable in Lightning Web Component

Viewed 510

When I am trying to change the value of an Api attribute in connected callback of my LWC, the value does not change. It retains the value coming from Parent. Please find example code below:

    export default class myLWC extends LightningElement{
    @api myApiVar={};//isNew is true in parent
    
    connectedcallback{
        Console.log(myApiVar.isNew);//true
        myApiVar.isNew=false;
        Console.log(myApiVar.isNew);//true
    
}

================================================= Please advice if I am missing anything here

1 Answers

Here you are trying to modify a public variable with api decorator which is not possible directly. You need to introduce a new Temp object to solve your purpose. You can modify your code to change as :

export default class myLWC extends LightningElement{
@api myApiVar={};//isNew is true in parent

connectedcallback{
    Console.log(myApiVar.isNew);//true
    let tmpObj = JSON.parse(JSON.stringify(myApiVar));
    
    tmpObj.isNew=false;
    myApiVar=tmpObj;
    Console.log(myApiVar.isNew);//false
    
}

=================================================

Please mark this as best answer if it works for you.

Related