How we handle dependent wire in LWC?
For example :
@wire(getObjectInfo, { objectApiName: OPP_OBJECT })
objectInfo;
@wire(getPicklistValues, {
recordTypeId: '$objectInfo.data.defaultRecordTypeId',
fieldApiName: STATUS_FIELD
})
pickListValues;
@wire(getRecord, { recordId: '$recordId', fields: FIELDS })
wiredRecord({ error, data }) {
if (ldsErrorHandling(error) && data) {
this._status = getFieldValue(data, STATUS_FIELD);
}
}
I have an operation that depends on the Stage Field of opportunity and also the picklist values. With normal promises or callbacks I can know when the two values are not null. If is a normal apex call we can have both information at the same time. But how we handle this type of situations with @wire
.
My solution for this (is this the only way?):
@wire(getObjectInfo, { objectApiName: OPP_OBJECT })
objectInfo;
@wire(getPicklistValues, {
recordTypeId: '$objectInfo.data.defaultRecordTypeId',
fieldApiName: STATUS_FIELD
})
handlePickValues({ error, data }) {
if (ldsErrorHandling(error) && data) {
this._data = data;
this.dependentLogic();
}
}
@wire(getRecord, { recordId: '$recordId', fields: FIELDS })
wiredRecord({ error, data }) {
if (ldsErrorHandling(error) && data) {
this._status = getFieldValue(data, STATUS_FIELD);
this.dependentLogic();
}
}
dependentLogic() {
if (this._status && this._data) //do logic
}
Thank you in advance
Best Answer
According to LWC docs:
Before understanding
dynamic and reactive
variable lets understandreactive
(that is , track).When track variable is re-assigned/changed in Javascript, LWC will re-render the DOM with updated track variables.
What will happen if
dynamic ('$objectInfo')
changes?Well, the wire functions dependent on this variable is triggered.
So, below code will work:
Reason: Here second wire will be triggered ONLY after first wire updates
objectInfo
. ThuspickListValues
will be updated after gettingobjectInfo
Important Notes: https://salesforcesas.home.blog/2019/07/23/dynamic-and-reactive-javascript-class-properties-in-lwc-track-wire-and/