1

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]

Apex:

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]; } }

LWC HTML:

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

LWC JS:

    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;
    @wire(findAccounts)
        wiredContacts({data, error}){
            if(data){
                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.

3

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.

| improve this answer | |
1

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>
   <template if:true={singleAccount}>
      <div> Problem is here ! {singleAccount.Name}</div>
   </template>
</template>
| 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.