How to use getRecord in LWC

When we have to fetch a single record from the database we don't have to do the song and dance of writing custom logic (using apex code) to fetch the record.

In this post, we will be looking at how to use getRecord() in LWC and fetch a single record.

When we have to fetch a single record from the database we don't have to do the song and dance of writing custom logic (using apex code) to fetch the record.

We can use the out-of-the-box methods (getRecord in this case) that Lightning Platform provides via LDS (Lightning Data Service) module.

Here are the series of steps that we need to implement to see that it works.

  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 account.
  4. Fetch the field values from the record using the method that we imported in step 1 i.e getFieldValue()
import { LightningElement, wire, api } from "lwc";

//1. import the methods getRecord and getFieldValue
import { getRecord, getFieldValue } from "lightning/uiRecordApi";

//2. Import reference to the object and the fields
import NAME_FIELD from "@salesforce/schema/Account.Name";
import RATING_FIELD from "@salesforce/schema/Account.Rating";
import INDUSTRY_FIELD from "@salesforce/schema/Account.Industry";

const fields = [NAME_FIELD, RATING_FIELD, INDUSTRY_FIELD];
export default class ExploreGetRecord extends LightningElement {
  @api
  recordId;

  //3. Wire the output of the out of the box method getRecord to the property account
  @wire(getRecord, {
    recordId: "$recordId",
    fields
  })
  account;

  renderedCallback() {
    console.log(this.account.data);
  }
  
  //4. Fetch the field values from the record
  get name() {
    return getFieldValue(this.account.data, NAME_FIELD);
  }

  get rating() {
    return getFieldValue(this.account.data, RATING_FIELD);
  }

  get industry() {
    return getFieldValue(this.account.data, INDUSTRY_FIELD);
  }
}

exploreGetRecord.js

It's a mandate that we provide the "recordId" in quotes and append a $ symbol in front of it. Because when the content of recordId is changed the apex method will be invoked again and the modified return value will be assigned back to the prop account.

This is how the template file is going to look like

<template>
    {name} <br />
    {industry} <br />
    {rating}
<template>

exploreGetRecord.html

Hope this was helpful!


💡
Grab your FREE course

I have put together a FREE course on Javascript that helps you master Lightning Web Components.

It just takes 2 hours to finish the course and you will be able to feel the difference.