I'm working with two lwc components. Both have a relationship parent-child. In my parent.js I wire an Apex class which contains an objects array:
Parent.js:
// imports...
export default class MyParent.js extends LightningElement {
currentUserProjects;
@wire(getProjectsForYear, { consultantId: '$consultantId', year: 2023 })
wiredProjectIdsForYear({ data, error }) {
if (data) {
this.currentUserProjects = data;
} else if (error) {
this.createErrorMessage(error.body.message);
}
}
this.currentUserProjects
retrieves the following object list:
[
{
"Name": "Test Session 1",
"test__Client__c": "Test Session 1",
"test__Start_Time__c": 32400000,
"test__End_Time__c": 36000000,
"test__Start_Date__c": "2023-03-08",
"test__End_Date__c": "2023-03-08",
"test__ID__c": "ID 215119",
"Virtual_Session_Link__c": "https://bts.zoom.us/",
"Id": "a0g59000000f21AAA"
}
]
In my parent.html:
<template>
<c-my-child-component projects={currentUserProjects}></c-my-child-component>
</template>
In my child.js:
// imports..
export default class MyChildComponent extends LightningElement {
@api projects;
connectedCallback() {
console.log(this.projects);
}
}
The problem is that console.log(this.projects);
at my child.js retrieves me an 'undefined' in the console while console.log(this.currentUserProjects);
at parent.js retrieves me the data correctly.
I tried defining another random variable and printing it at my child.js and works, so I guess something is wrong with my this.currentUserProjects
.
Hope someone could help with this.
SOLUTION: The problem was the child component was being rendered before my parent wire has returned the data, so I did the following:
Parent.html:
<template>
<template if:true={loadingcomplete}>
<c-my-child-component projects={currentUserProjects}></c-my-child-component>
</template>
</template>
Parent.js:
// imports...
export default class MyParent.js extends LightningElement {
currentUserProjects;
loadingcomplete = false;
@wire(getProjectsForYear, { consultantId: '$consultantId', year: 2023 })
wiredProjectIdsForYear({ data, error }) {
if (data) {
this.currentUserProjects = data;
this.loadingcomplete = true;
} else if (error) {
this.createErrorMessage(error.body.message);
}
}
}
The console.log in my child.js printed a me a Proxy {} so I did a parse to my data:
connectedCallback() {
const accounts = JSON.parse(JSON.stringify(this.projects));
console.log(accounts);
}
Now the information is been printed in my child.js correctly. :) Hope this helps!