I want to pass an Array of Objects from a parent to child component. The child component will modify this array (but not perform a DML). This is what i tried
somewhere in parent.js
@track tempList = [];
connectedCallback(){
getCourseModules({courseId:this.recordId})
.then(result =>{
this.moduleList = result;
this.moduleList.forEach(item=>{
var a = {};
a.id = item.LM__c;
a.navigate = item.LM_c;
a.label = item.ModName__c;
a.order = item.Order__c;
this.tempList.push(a);
});
})
.catch(error => {
console.error(error);
})
}
Somewhere in parent.html
<template>
<c-child title="Modules" item-list={tempList} ></c-child>
</template>
Somewhere in child.js
@api
set itemList(value){
this.privateItemList = value;
//shallow copy the array
this.list = [...value];
}
get itemList(){
return this.privateItemList;
}
Somewhere in child.html
<template iterator:item={list}>
<tr key={item.value.id}>
<td>{item.value.order}</td>
<td><lightning-button label={item.value.label} data-index={item.value.navigate} variant="base" onclick={linkClick}></lightning-button></td>
</template>
I don't see anything rendering in the child component.
Workaround-
//shallow copy the array in parent.js like this
this.moduleList = result;
this.moduleList.forEach(item=>{
var a = {};
a.id = item.LM__c;
a.navigate = item.LM_c;
a.label = item.ModName__c;
a.order = item.Order__c;
this.tempList.push(a);
});
this.tempList = JSON.parse(JSON.stringify(this.tempList));
//shallow copy the array in child.js like this
@api
set itemList(value){
this.privateItemList = value;
//shallow copy the array
this.list = JSON.parse(JSON.stringify(value));
}
This is working. I wanted to understand-
- If this approach of JSON.parse + JSON.stringify might break with future releases of LWC (is it stable enough ?)
- Is there a more stable way to passing arrays (that need to be mutated by the child)
- Will this approach cause performance issues ? I hope not, because i'm creating a copy of my original Array and not a reference.