0

I am getting the below error

Cannot read properties of undefined (reading 'Name')

The code for the LWC Component and controller is shown below.

ContactController.cls

public with sharing class ContactController {
    @AuraEnabled
    public static List<Contact> getContacts(){
        return [SELECT Id, FirstName, LastName,AccountId,Account.Name FROM Contact];
    }
}

contactDataTable LWC Component

<template>
    <lightning-card title="Change-3">
        <lightning-datatable
            key-field = 'id'
            data ={result}
            columns={columnsList}>
        </lightning-datatable>
    </lightning-card>
</template>

js file ==>

import { LightningElement,wire,track,api } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';

const columns = [
    { label: 'First Name', fieldName: 'FirstName' },
    { label: 'Last Name', fieldName: 'LastName' },
    { label: 'Account Name', fieldName: 'AccountName' }
];

export default class ContactDataTable extends LightningElement {
    @api result;
    @track error;

    columnsList = columns;

    connectedCallback(){
        this.getAllContacts();
    }

    getAllContacts(){
        getContacts()
        .then(data => {
            data.forEach(conRec => {
                console.log('Contact Record-->', conRec)
                conRec.AccountName = conRec.Account.Name;
            })
            this.result = data;
            window.console.log('conData', data);
            this.error = undefined
        })
        .catch(error => {
            this.error = error;
            window.console.log('conError', error);
            this.result = undefined
        })
        
    }
}

The error screenshot below

enter image description here

Debugger Showing Failing Line

enter image description here

1
  • 2
    It looks like it's erroring out because the Account on the Contact is undefined (null). Is the Contact record linked to an Account?
    – Instread
    Jan 20, 2022 at 23:46

1 Answer 1

1

The issue is because you have contact records in the system that does not have Accounts linked.

Hence there is an undefined assignment that happens in the below line

conRec.AccountName = conRec.Account.Name;

The conRec.Account is undefined for few records and you are trying to access Name property of the undefined.

To fix this you can use an optional chaining or a simple if statement to check for undefined.

With Optional Chaining (does not work for IE though)its one line fix as shown below

    conRec.AccountName = conRec.Account?.Name;
1
  • Thanks Buddy, Your answer really saved my day Jan 21, 2022 at 3:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .