[SalesForce] Unable to access recordTypeInfo using getObjectInfo of lightning/uiObjectInfoApi API in lwc

I'm trying to retrieve recordTypeInfo, & create a map of RecordType name & RecordType Id, for a custom object using getObjectInfo adapter from lightning/uiObjectInfoApi API, based on this example
(https://developer.salesforce.com/docs/component-library/documentation/lwc/reference_wire_adapters_object_info).

This component is added on Lightning Record Page.

I keep receiving [Cannot read property 'data' of undefined] error.
Sample Error

Below is my code:-


opptyapplicationlist.html

<template>
    <lightning-textarea value={recTypeMap} label="RecordType"></lightning-textarea>
</template>

opptyapplicationlist.js

import {LightningElement, track, wire, api} from 'lwc';
import {getObjectInfo} from 'lightning/uiObjectInfoApi';
import APPLICATION_OBJECT from '@salesforce/schema/Application__c';

export default class OpptyApplicationList extends LightningElement {
    @api recordId;
    @track recTypeMap = this.getAppRecType();
    @wire(getObjectInfo, {objectApiName: APPLICATION_OBJECT}) objectInfo;

    getAppRecType() {
        const rtis = this.objectInfo.data.recordTypeInfos;
        return Object.keys(rtis).find(rti => rtis[rti].name === 'SBV MasterClass');
    }
}

Is there something amiss in the example, or am I missing something very obvious.

Best Answer

Your issue:

Cannot read property 'data' of undefined

is because you are trying to refer to a property even before it has been declared. In your current JS, you are referring to objectInfo even before it is available.

Resolution

Declare a JS function which should return the Record Type Id only when the component has been rendered. And then utilize that JS function in your HTML. So your JS looks like:

// remove declaration of @track recTypeMap; this is not required at all 

@wire(getObjectInfo, {objectApiName: APPLICATION_OBJECT}) objectInfo;

// this is a getter function now, see get keyword
get getAppRecType() {
    const rtis = this.objectInfo.data.recordTypeInfos;
    return Object.keys(rtis).find(rti => rtis[rti].name === 'SBV MasterClass');
}

Now, in HTML, make sure to verify for objectInfo.data before calling the function as the data will be available only when the component has finished rendering.

<div if:true={objectInfo.data}>
    {getAppRecType}
</div>
Related Topic