0

Problem is with this line in JS code inside result function- return this.wirestoredrecords.data.LastName;

I am trying to get the Contact Fields Values using Getter and display in the HTML. PLS HELP.

**JS CODE:**

import { api, LightningElement, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
import Name from '@salesforce/schema/Contact.Name';
import LastName from '@salesforce/schema/Contact.LastName';
import Phone from '@salesforce/schema/Contact.Phone';

const contactfields = [Name, LastName, Phone];

export default class WireGetRecords extends LightningElement {
    @api recordId;
    datavalue;

    @wire(getRecord, { recordId: '$recordId', fields: contactfields })
    wirestoredrecords;

    get result(){

        return this.wirestoredrecords.data.LastName;

    }

}

**HTML CODE:**
<template>
    <lightning-card>
        <div>{recordId}</div>
        <div>{result}</div>
        <div></div>
    </lightning-card>
</template>```

Praveen Behera
  • 444
  • 2
  • 8
  • 17

1 Answers1

1
  1. Your component loads to the page and the @wire is called.
  2. The component doesn't wait for @wire to finish, it'll be done when it'll be done, asynchronous. Your component carries on.
  3. It encounters the html rendering, calls your getter. Well, the variable is undefined/null at that point, @wire didn't return yet. The code tries to do null.data and throws because null/undefined doesn't have fields.
  4. Boom, headshot.

Put some null checking in the getter or use the ?. operator

eyescream
  • 18,088
  • 2
  • 34
  • 46
  • How to use in my case, can you please help me with that? – Praveen Behera Mar 10 '22 at 08:20
  • Try `this.wirestoredrecords?.data?.LastName;` or `return this.wirestoredrecords && this.wirestoredrecords.data ? this.wirestoredrecords.data.LastName : 'Loading...':` – eyescream Mar 10 '22 at 08:51
  • OMGGG, this line worked - return this.wirestoredrecords?.data?.fields?.Name?.value; But how. Why it worked with that symbol? I will study more on it. Thanks a ton @eyescream. – Praveen Behera Mar 10 '22 at 09:08