Sub topic 4
Reading a record with getRecord
This chapter assumes you can write a basic Lightning web component (HTML template, JavaScript class, metadata file). It also assumes you know the @api decorator, the recordId property on record pages, and ES modules, promises, and async/await. Earlier chapters introduced Lightning Data Service, @wire, and schema imports. This chapter puts them together to read one record.
What getRecord does
getRecord is a wire adapter exported by lightning/uiRecordApi. You give it a record ID and a list of fields. It returns an object with the field values for that record. The request goes through Lightning Data Service (LDS), which keeps a shared client-side cache. If another component on the page already loaded the same record and fields, LDS can answer from the cache. It does not need another server call.
Key properties of getRecord:
- It is read-only. To change data you call
updateRecord, which is covered in a later chapter. - It respects the running user's object permissions, field-level security, and sharing. Fields the user cannot see are not returned, or they cause an error, depending on how you requested them.
- It is reactive when you use
$-prefixed parameters, so the component re-reads the record when an input changes. - It needs no Apex.
The basic pattern
The example below wires getRecord to a property named account. It reads the name and the industry of the current record.
import { LightningElement, api, wire } from 'lwc';
import { getRecord, getFieldValue, getFieldDisplayValue } from 'lightning/uiRecordApi';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import INDUSTRY_FIELD from '@salesforce/schema/Account.Industry';
export default class AccountSummary extends LightningElement {
@api recordId;
@wire(getRecord, {
recordId: '$recordId',
fields: [NAME_FIELD],
optionalFields: [INDUSTRY_FIELD]
})
account;
get name() {
return getFieldValue(this.account.data, NAME_FIELD);
}
get industry() {
return getFieldDisplayValue(this.account.data, INDUSTRY_FIELD);
}
}Four things happen here:
@salesforce/schema/Account.Nameimports a field reference. It is an object withobjectApiNameandfieldApiName. The platform checks that the field exists, and it tracks the dependency. If someone tries to delete the field, Salesforce can warn them.recordId: '$recordId'tells the wire service to readthis.recordIdand to provision again when it changes.fieldslists required fields.optionalFieldslists fields that are fetched when the user can access them.accountreceives an object with two properties,dataanderror.
Rendering the result
The wire provisions values asynchronously. When the component first renders, account.data is undefined. The template has to cope with that.
<template>
<template lwc:if={account.data}>
<p>Name: {name}</p>
<p>Industry: {industry}</p>
</template>
<template lwc:if={account.error}>
<p>The record could not be loaded.</p>
</template>
</template>The getters are also safe before data arrives, because getFieldValue returns undefined when the record is undefined. The lwc:if guards still matter, because they keep labels such as "Name:" off the screen while the component loads.
How the wire runs
The sequence below shows what happens from component creation to rendering.
If recordId is undefined when the component connects, the wire does not run. It waits. When recordId receives a value, the wire runs. This is the reason the $ prefix is useful.
Reactive parameters
Without a $, a string is a literal. recordId: 'recordId' would send the text "recordId" as the ID. With $recordId, the wire service resolves this.recordId and watches it.
Rules:
- The
$value is a property name on the component, such as'$recordId'. It can also be a path like'$selected.id'. - Only the
$-prefixed parameters are reactive. Thefieldsarray in the example is static. - When any reactive parameter is
undefined, the wire does not call the adapter. Thedataanderrorvalues stay as they were. - When a reactive parameter changes, the wire runs again, and the property is updated with the new result.
Gotcha: stale data on change
Because the wire does not call the adapter while a parameter is undefined, a component that clears recordId can still show the previous record. If that matters, guard your template or reset your own state when the ID is cleared.
Fields and optionalFields
You must say which fields you want. getRecord does not return every field.
| Property | If the user cannot access a field | When to use it |
|---|---|---|
| `fields` | The whole request fails with an error. No record data is returned. | Data the component cannot work without. |
| `optionalFields` | The field is left out. The rest of the record is returned. | Data that can be missing, or fields that profiles may not see. |
A request can combine both. Use fields sparingly. One inaccessible required field makes the whole component show an error. For fields that vary by profile, or that exist only in some orgs, optionalFields is safer.
Additional points:
- Pass field references from
@salesforce/schema, not strings, whenever you can. Strings such as'Account.Name'work, but they do not give you the dependency tracking. - You can use cross-object fields, for example
@salesforce/schema/Account.Owner.Name. The related record is returned in thefieldsof the main record. - The old
layoutTypesandmodesparameters belong to a different mode of the adapter. They cannot be mixed withfieldsoroptionalFields. - Cached results are keyed by record and by the fields requested. A new component that asks for more fields than the cache holds causes a new request for the extra fields.
Handling data and error
The result of a wire has two shapes. When the read works, data has the record and error is undefined. When it fails, error has the details and data is undefined. The wire provisions a new object for each result, so do not edit data in place. The object is read-only.
What data looks like
data is a record object. Its important parts are:
id, the record ID.apiName, for exampleAccount.fields, an object whose keys are field API names. Each entry has avalueand adisplayValue.recordTypeIdandrecordTypeInfo, when the object uses record types.
You can read data.fields.Name.value, but the helper functions are better. They handle missing fields and relationship paths.
getFieldValue and getFieldDisplayValue
Both helpers take a record and a field reference.
| Helper | Returns | Example result for a picklist, Industry |
|---|---|---|
| `getFieldValue(record, field)` | The raw value stored in the field. | `"Agriculture"` (the API value) |
| `getFieldDisplayValue(record, field)` | The value formatted for display, such as a translated label or a formatted number or date. | `"Agriculture"` in the user's language |
Notes on their behavior:
- Both return
undefinedwhen the field is not in the record. This happens when you listed it inoptionalFieldsand the user has no access. getFieldDisplayValuecan also returnundefinedfor fields that have no separate display value, such as plain text. Fall back togetFieldValuewhen you need a value that is always present.- For currency, date, and picklist fields, the display value follows the user's locale.
A safe fallback looks like this:
get industry() {
return (
getFieldDisplayValue(this.account.data, INDUSTRY_FIELD) ??
getFieldValue(this.account.data, INDUSTRY_FIELD)
);
}Wiring to a function
Wiring to a property is the simplest option. Wire to a function when you want to run logic on every result, such as copying values into your own properties.
import { LightningElement, api, wire } from 'lwc';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';
import NAME_FIELD from '@salesforce/schema/Account.Name';
export default class AccountNameLogger extends LightningElement {
@api recordId;
name;
errorMessage;
@wire(getRecord, { recordId: '$recordId', fields: [NAME_FIELD] })
wiredAccount({ data, error }) {
if (data) {
this.name = getFieldValue(data, NAME_FIELD);
this.errorMessage = undefined;
} else if (error) {
this.errorMessage = error.body && error.body.message;
this.name = undefined;
}
}
}The function is called each time a new result arrives, with one argument: an object with data and error. Reset the value you are not setting. Otherwise an old error stays on screen after a later read works, or the old name stays after a read fails.
Choose between the two forms like this:
- Property: less code, and the template reads
account.dataandaccount.errordirectly. - Function: you need side effects, or you want to transform or store the result in your own fields.
Error handling for reads
An error from getRecord is an object in the shape of a fetch response. The readable text is usually in error.body.message. Common causes:
- The record does not exist or was deleted (a not found error).
- The user has no access to the record.
- A field in
fieldsis not accessible or does not exist. - A network failure.
Two defensive habits help:
- Read the message with a guard, as in
error.body && error.body.message. Some errors, such as network failures, have nobody. - Show the user a short message in the template. Log the full error with
console.errorwhile you develop.
Common mistakes
- Using
recordId: 'recordId'without the$. The adapter receives a literal string and returns an error. - Reading
this.account.data.fields.Name.valuein a getter without checkingdata. It throws while the wire is still loading. - Modifying
data. The object is frozen. Copy the values you need. - Importing a field from the wrong object, such as
Contact.Namein an Account component. It will request a field that does not belong to the record. - Expecting
getRecordto return fresh data after an Apex change. LDS does not know about server changes made outside it. The chapter ongetRecordNotifyChangecovers this.
Check your understanding
Exercise
A component wires getRecord with fields: [NAMEFIELD, REVENUEFIELD]. Users on one profile cannot see AnnualRevenue, and for them the component shows only an error message. What change fixes it for those users, and why?
Show answer
Move REVENUE_FIELD from fields to optionalFields. A required field that the user cannot access makes the whole request fail. An optional field is simply left out of the result, so the record loads and getFieldValue returns undefined for the missing field. The template can then hide or replace the revenue line.
Exercise
Your wire uses recordId: 'recordId' and the component never shows data. What is wrong, and what does the corrected line look like?
Show answer
Without the $ prefix, the wire sends the literal text "recordId" as the ID. Write recordId: '$recordId' so the wire service reads this.recordId and provisions again when it changes.