I have an apex which return list of Account and related Contacts to it. Now that I KNOW how to iterate thru' list of account but I am interested in 1st element of the list.So,I am trying to display the same on HTMl but giving me the below error. pls suggest. I am intersted in 1st element of the list alone.

Error Message on component load : afterRender threw an error in 'c:apexClassExample' [Cannot read property 'Name' of undefined]


public with sharing class AccountController { @AuraEnabled(cacheable=true) public static List<Account> findAccounts() { return [SELECT Id, Name, (Select Id, Name from contacts), AccountNumber from Account Limit 10]; } }


    <div> Problem is here ! {singleAccount.Name}</div>


    import { LightningElement,track,wire } from 'lwc';
import findAccounts from '@salesforce/apex/AccountController.findAccounts';
export default class ApexClassExample extends LightningElement {
    @track accounts;
    @track singleAccount;
    @track error;
        wiredContacts({data, error}){
                this.accounts = data;                
                this.singleAccount = data[0];
                console.log('Single >>'+JSON.stringify(this.singleAccount, null, '\t'));
                this.error = undefined;
            else if (error) {
                this.error = error;
                this.accounts = undefined;


However the console log "Single >> " is giving me the expected 1st element but unable to bring the same data back to HTML.

2 Answers 2


singleAccount is declared by initialising to null. So even before wired function gets back the data, the template is trying to display singleAccount.Name which is throwing error.

Change it to:

@track singleAccount = {};

Now its initialised Object, so you will not get error.

As Martin Lezer, pointed, you can also include empty check <template if:true={singleAccount}>.

As a good practice, always initialise Objects and Arrays (non-primitive data types) during declaration.


The problem is that the view tries to load your variable, namely singleAccount, before the Apex method is called by the wire service.

The variable being undefined, it raises the error.

For this reason, it is always necessary to check that the data is present before trying to load it in the view.

You just have to replace your code by the below code in your template.

   <template if:true={singleAccount}>
      <div> Problem is here ! {singleAccount.Name}</div>

You must log in to answer this question.

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