I noticed that the security for immutable @api properties is increased but unable to find any documentation.
Consider below LWC component:
HTML:
<lightning-button variant="brand" onclick={sortFruits} label="sortFruits"></lightning-button>
<template for:each={fruits} for:item="ft" for:index="ind">
<div key={ft}>
{ind}: {ft}
</div>
</template>
JS:
@api fruits;
sortFruits() {
this.fruits.sort();
}
We should pass the array fruits from parent component like below Aura parent component:
<aura:attribute name="fruits" type="List" default="['Banana', 'Orange', 'Apple', 'Mango']" />
<c:poc fruits="{!v.fruits}" />
When you click on button sortFruits, it will throw error
Invalid mutation: Cannot set "0" on "Banana,Orange,Apple,Mango". "Banana,Orange,Apple,Mango" is read-only. at ReadOnlyHandler.set
Solution:
This can be fixed using this.fruits = [...this.fruits].sort();
.
Question:
1. This started throwing error only in winter 20 upgrade and not before. Ofcourse, it is logical error but I do not find any documentation regarding this change so that our developers can do required changes in existing LWC components – not just for sort() but also for any other potential JS functions where code can break
2. When I say this.fruits =
, I am actually modifying the data which came from parent. This is working today, but will this work in future? And is reassigning not same as mutating data – in what way they are different?
Best Answer
The closest I can find (in the LWC dev guide) is: