0

I'm trying to make a basic with the @wire method on the contact record to pull in a phone number. But the error I keep getting is

  • Cannot read property 'fields' of undefined on c:ParentElement
  • Cannot read property 'fields' of undefined on c:ChildElement

Anyone ever had this problem before? I have a feeling it has to do with the execution order of the LWC and the data not getting in there, but I'm not sure how to go about fixing that issue.

Parent html

<template if:true={objectApiName}>
            Contact
            <c-child-element get-object-from-parent={objectApiName} get-record-id-from-parent={recordId}></c-child-element>
</template>

Parent js

import { LightningElement, track, api, wire } from 'lwc';


export default class ParentElement extends LightningElement {
    @api objectApiName; // contact object

    @api recordId; //contact record id

Child html

<template>
<lightning-card>
    <div class="slds-text-heading_medium slds-text-align_center">
        Record Id : {getRecordIdFromParent}
    </div>
    <div class="slds-text-heading_medium slds-text-align_center">
        Object Name : {getObjectFromParent}
    </div>
    <div class="slds-text-heading_medium slds-text-align_center">
        ContactPhone : {contactPhone}
    </div>

</lightning-card>

Child JS

import { LightningElement, api, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';


export default class ChildElement extends LightningElement {
    @api getRecordIdFromParent;
    @api getObjectFromParent;
    @api contactPhone;


    @wire(getRecord, {recordId: '$getRecordIdFromParent', fields:['Contact.Phone']})
    contact;


    get contactPhone() {
        return this.contact.data.fields.Phone.value;
    }

Thanks for your help!

  • I may have figured it out using <template if:true = {contact.data}> ...... </template> seems like it was the issue with trying to load the Record Id: Object Name: in the HTML before it got into the JS of the child element? – thinker May 29 at 21:44
  • Any insight into why this works, would be helpful. Still not sure why. – thinker May 29 at 21:45
2

Wire methods load their data asynchronously, so you'll go at least one render() cycle before the data is available. You do need to check for null values to avoid this error.

There's a handy utility method to avoid having to check for null values, etc:

import { getFieldValue } from 'lightning/uiRecordApi';
import CONTACTPHONEFIELD from '@salesforce/schema/Contact.Phone';

...

get contactPhone() {
    return getFieldValue(this.contact.data, CONTACTPHONEFIELD);
}
| improve this answer | |

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.