0

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?

1 Answer 1

2

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;
}
7
  • thanks for that. I understand that it's a method and that was a miss from my end. However, I'm still getting the same error when I change it back to a property. Updated my code. Commented Mar 31, 2020 at 17:23
  • @AshutoshArora As I demonstrated near the end, check to see if this.record is populated first: return this.record && this.record.data.fields.Name.value
    – sfdcfox
    Commented Mar 31, 2020 at 19:02
  • I tried that too, it didn't fix the error. Commented Mar 31, 2020 at 19:04
  • I commented out {accountName} from template and added a button which calls a js method.. I used console.log('?? : ',this.record.data.fields.Name.value) to see if this prints the value.. this actually works, I am able to see the account name in console.. Can this be because getters are called before wire executes? Commented Mar 31, 2020 at 19:16
  • @AshutoshArora What about getFieldValue? developer.salesforce.com/docs/component-library/documentation/…
    – sfdcfox
    Commented Mar 31, 2020 at 19:16

You must log in to answer this question.

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