getRecord

Fetch Salesforce Record in LWC without Apex

LWC, AURA

How to use getRecord() in LWC and fetch a single record without Apex method. For solution we can use the out of the box methods (getRecord)

Below steps that we need to implement to see that in working.

  1. Import the named imports getRecord() and getFieldValue() from the package lightning/uiRecordApi.
  2. Import the reference to the fields that we wish to display back to the users.
  3. Wire the output of the out of the box method getRecord() to the property contact.
  4. Fetch the field values from the record using the method that we imported in step 1 i.e getFieldValue()

For this approach, i have created a LWC component

fetchContactRecord.html

<template>
    <div class="slds-m-around_medium">
        <p>First Name: {fName}</p>
        <p>Last Name: {lName}</p>
        <p>Phone: {conPhone}</p>
        <p>Email: {conEmail}</p>
    </div>
</template>

fetchContactRecord.js

import { LightningElement, wire } from 'lwc';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';
import FNAME_FIELD from '@salesforce/schema/Contact.FirstName';
import LNAME_FIELD from '@salesforce/schema/Contact.LastName';
import PHONE_FIELD from '@salesforce/schema/Contact.Phone';
import EMAIL_FIELD from '@salesforce/schema/Contact.Email';


export default class FetchContactRecord extends LightningElement {
    @wire(getRecord, { recordId: '0035h00000vvtQNAAY', fields: [FNAME_FIELD, LNAME_FIELD,PHONE_FIELD, EMAIL_FIELD] })
    contact;

     get fName() {
        return getFieldValue(this.contact.data, FNAME_FIELD);
    }

    get lName() {
        return getFieldValue(this.contact.data, LNAME_FIELD);
    }

    get conPhone(){
        return getFieldValue(this.contact.data, PHONE_FIELD);
    }
    
    get conEmail() {
        return getFieldValue(this.contact.data, EMAIL_FIELD);
    }

}

fetchContactRecord.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>56.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
      <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

uniquesymbol

Leave a Reply