-1

I am Unable to fetch custom object field label and use it in my LWC's html component. My objective is to fetch the custom object field label and use it in header of a table in LWC html.

Code is like below -

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

export default class Poc extends LightningElement {
@track oppInfo;

@wire(getObjectInfo, { objectApiName: OPPORTUNITY_OBJECT })
oppInfo;

get StageLabel() {
    return this.oppInfo.data.fields.StageName.label;
 }

}

and using the StageLabel parameter in the table header like {StageLabel}

but getting the error Cannot read property 'fields' on undefined

Please help how to fix it.

0

This is probably happening because when your component initially renders and invokes StageLabel, and this.oppInfo still hasn't retrieved the data from the wire method.

you can add a type check to your properties or check the properties in the chain to ensure that they are not undefined before rendering by using Optional chaining (?.)

example:

this.oppInfo?.data?.fields?.StageName?.label;

additionally, you can use a Nullish coalescing operator (??) to default the value if there is an undefined value as follows:

this.oppInfo?.data?.fields?.StageName?.label ?? 'some value'

Additionally, you might want to use a property function instead of oppInfo to troubleshoot further, ex:

@wire(getObjectInfo, { objectApiName: OPPORTUNITY_OBJECT })
    wiredOpp({ error, data }) {
            if (data) {
                //Do something          
            } else {
                this.error = error;
                //Do something
            }
        }
4
  • I tried with the Nullish coalescing operator and that works. but it always renders the default value. My main objective here is to show the field label based on the user's language. which is not happening here. Any idea how to display field label in native user's language translation? Sep 2 at 17:50
  • that means that your data might not begetting fetched correctly from your wired method, consider using a proeprty function instead. updated my post
    – glls
    Sep 2 at 17:51
  • yes there is an error it seems. but cannot see what error it is - when trying to print JSON.stringify(error.body.message) it shows cannot read property 'body' of undefined Sep 2 at 18:18
  • were you able to figure this out? the root cause is the same as the answer provided, you need to handle how you access json properties correctly, and add error handling.
    – glls
    Sep 3 at 12:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.