[SalesForce] Cannot read property ‘fields’ of undefined

I'm using getter to display data fetched using wire service in lwc html and getting and error :

Cannot read property 'fields' of undefined

Below is the piece of code:

HTML

<template>
    <lightning-card title="Basic Wire Example!"></lightning-card>
    <p>Account Name : {accountName}</p>
</template>

JS

import { LightningElement , api, wire} from 'lwc';
import {getRecord} from 'lightning/uiRecordApi';
import Name from '@salesforce/schema/Account.Name';
export default class WireBasic extends LightningElement {
    @api recordId;
    @wire(getRecord , {recordId : '$recordId', fields: [Name]}) record;
    get accountName(){
        return this.record.data.fields.Name.value;
    }
}

The error is actually triggered from get accountName. I used so many console logs to understand the order of execution and understand that connectedcallback is called before wire and maybe getter too is being called before wire assigns the value to record.
Is there a way to ensure that getter isn't called till a value is assigned by wire? How can I make this work?

Best Answer

record is a method, not a property. Given your current code, you could just:

get accountName() {
  return this.sAcctName;
}

The only time you'd use this.record.data... would be if you used the wire annotation as a property:

@wire(getRecord, { recordId: '$recordId', fields: [Name]) record;

...

get accountName() {
    return this.record && this.record.data.fields.Name.value;
}
Related Topic