I'm trying to get the timing of some setup code in an LWC to be reliable. The code needs the opportunity record type Id so it can get the correct picklist values. Then with those picklist values (and some other async data) I'm creating the data structure that my UI needs.
The code I am using is below. While the await
for the opportunity record type Id does block, meanwhile the getPicklistValues
wire adapter will often have completed for the initial undefined _opportunityRtId
value so the next await
falls through before the getPicklistValues
wire adapter has run again with the correct _opportunityRtId
value.
I'm pretty obviously approaching this problem the wrong way. But imperative calls here are not available AFAIK and based on Can we call LWC wire adapters imperatively?. And I get that wire adapters can react to changes in '$...'
arguments to offer a form of chaining. And also Chain wire methods together in Lightning Web Components.
Is there a pattern where the code can wait for a chain of @wire
calls to settle and then run some code once only? Do you need to set completion flags for each @wire
and then when all complete run the code?
_opportunityRtId;
async init() {
const rtis = await this._opportunityObjectInfo.data.recordTypeInfos;
this._opportunityRtId = Object.keys(rtis).find(
rti => rtis[rti].name === '...'
);
const results = await Promise.all([
this._opportunityPicklistValues,
...
]);
const r0 = results[0];
// Initialisation code that uses the picklist values r0.data.values
// and other async results
}
@wire(getObjectInfo, {
objectApiName: OPPORTUNITY_OBJECT
})
_opportunityObjectInfo;
@wire(getPicklistValues, {
recordTypeId: '$_opportunityRtId',
fieldApiName: OPPORTUNITY_TYPE_FIELD
})
_opportunityPicklistValues;
getPicklistValues
wire a functionwiredPicklistValues({ error, data })
that calls, when data is actually returned, within it whatever init function/logic you need? If you do the same for the object info wire, you'd control when_opportunityRtId
gets set and, based on what i'm seeing, have the picklist wire function "last"?checkForComplete
function that only executes if both pieces of data are present. Note the wire callback is called multiple times making this more painfulgetPicklistValues
call returns the wrong data when_opportunityRtId
is undefined, so I can guard my logic by checking that. When_opportunityRtId
is set to the right value,getPicklistValues
will run again, and this time with_opportunityRtId
not undefined I can run my logic. Think that may be it.