Cannot read properties of undefined (reading ‘data’)

lightning-web-componentslwc-wire-adapter

I'm trying to pass the "CID" variable into the second wire statement, however I keep getting an error when I run it, "Cannot read properties of undefined (reading 'data')". This, I assume, is referring to the CID declaration statement. I should note that I am relatively new to LWC and Salesforce so there may be a simple solution to this that I am simply not aware of.

import Contact_ID_FIELD from '@salesforce/schema/Project_Contact__c.Contact_ID__c';
import CONTACT_SMS_PERMISSION_FIELD from '@salesforce/schema/Contact.SMS_Permission__c';


export default class PhoneManagement extends LightningElement
{
    
    @api recordId;
    smsPermission;
    ContactAccount;
    smsIcon;

    @wire(getRecord, { recordId: '$recordId', fields: [Contact_ID_FIELD] })ProjectAccount;

    CID = getFieldValue(this.ProjectAccount.data, Contact_ID_FIELD);
    
    get contactID()
    {
        return getFieldValue(this.ProjectAccount.data, Contact_ID_FIELD);
    }
    get smsPermission()
    {
        return this.smsPermission;
    }

    @wire(getRecord, { recordId: this.CID, fields: [CONTACT_SMS_PERMISSION_FIELD] })
    wiredRecord({ data, error })
    {
        if (data)
        {
            this.ContactAccount = data;
            this.smsPermission = this.ContactAccount.fields.SMS_Permission__c.value;
        }
        else if (error)
        {
            console.error(error);
        }
    }

Best Answer

You can directly use contactID in the second wired method by making it reactive.

Remove below line:

CID = getFieldValue(this.ProjectAccount.data, Contact_ID_FIELD);

Update second wire method:

@wire(getRecord, { recordId: '$contactID', fields: [CONTACT_SMS_PERMISSION_FIELD] })
wiredRecord({ data, error }){
 //...add logic
}

Also, do not use same name for private property as well as getter method. Remove below code:

get smsPermission(){
  return this.smsPermission;
}
Related Topic