[SalesForce] two wires (getRecord, getObjectInfo) in a single in Lightning Web Components (LWC). Need to chain one after the other

I'm trying to fetch the record values and show the label of the fields that have null values on the record detail page.

The code snippet is as below:

objectInfo = {};

@wire(getObjectInfo, {objectApiName: Lead_OBJECT })
LeadInfo({ data, error }) {
    if (data) {
        this.objectInfo = data;
    }
}

@wire(getRecord, {
    recordId: "$recordId",
    fields: ['Company']
})
lead({error, data}) {
    if (data) {
        if (!data.fields['Company'].value) {
            console.log(this.objectInfo.fields['Company'].label);//getting an error here
        }
    }
}

Error is objectInfo is undefined certain times and doesnt understand objectInfo.fields. This doesn't happen every time I load the page, only sometimes this error occurs on refresh. I understand this is because both run asynchronously. what is the way to make this work?

Best Answer

I do something similar to get picklist values for a certain record type, and this works for me - I get the object info, assign the record type I need to the accountRTID variable, which in change triggers the picklist value lookup

import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import STATEOFREP_FIELD from '@salesforce/schema/Account.kw__StateOfCoverage__c';

export default class myClass extends LightningElement {
objectInfo;
accountRTID;

@wire(getObjectInfo, { objectApiName: ACCOUNT_OBJECT })
wireObject(result) {
    if (result.data) {
        this.objectInfo = result.data;
        const rtis = this.objectInfo.recordTypeInfos;
        this.accountRTID = Object.keys(rtis).find(rti => rtis[rti].name === 'KW - Member');
    } else if (result.error) {
        this.error = result.error;
    }
}

@wire(getPicklistValues, { recordTypeId: '$accountRTID', fieldApiName: STATEOFREP_FIELD })
stateOptions;

I can then reference the stateOptions value in my component

Related Topic