[SalesForce] How to pass the value from parent component to child component on load in LWC

I have this scenario. I am having a getRecord wire method in parent component which is assigning a field value to the variable. That value is passed to the child component. I have a connectedCallback() function in the child component which is having some logic based on the value passed through the parent component.

Issue: The wire method in parent component is running after the connected callback() function in the child component and getting the value as undefined even though the record has value on that field. Can anyone help in resolving this.

Parent Component:
JS

import STATUS_FIELD from @salesforce/schema/customObject__c.status__c;
import { getRecord } from 'lightning/uiRecordApi'

const FIELDS = [STATUS_FIELD];

@api recId
@track status;
@track error;

@wire(getRecord, {recordId: '$recId', fields: FIELDS}) details({error,data}) {
if(data) {
this.status = data.fields.status__c.value;
} else {
this.error = error;
}
}

HTML (calling child component)

<template >
<child-component status-value={status} >
</child-component>
</template>

CHILD Component

JS

@api statusValue;

connectedCallback() {

if(this.statusValue == 'Finished'){
//some logic
}
}
//statusValue is coming as undefined here but the value is actually Finished.

Best Answer

Make the following changes in parent component and it will start working.

Parent Component: JS

import STATUS_FIELD from @salesforce/schema/customObject__c.status__c;
import { getRecord } from 'lightning/uiRecordApi'

const FIELDS = [STATUS_FIELD];

@api recId
@track status;
@track error;
@track flagIndicatingDataHasBeenLoadedInVariables = false;

@wire(getRecord, {recordId: '$recId', fields: FIELDS}) details({error,data}) {
if(data) {
this.status = data.fields.status__c.value;
this.flagIndicatingDataHasBeenLoadedInVariables = true;
} else {
this.error = error;
}
}

HTML (calling child component)

<template if:true={flagIndicatingDataHasBeenLoadedInVariables}>
     <child-component status-value={status} >
     </child-component>
</template>

Explanation: We are setting a flag after the data is loaded. Only after data is loaded in the parent, it will be passed to the child component.

Related Topic