Sub topic 7
Working with data and error from the wire
This chapter covers what a getRecord wire gives your component, how to read it, and how to avoid the mistakes that come with it. It assumes you know JavaScript modules, promises and async/await, the structure of a Lightning web component, the @api decorator with recordId on record pages, and basic Salesforce objects, fields, and record IDs. Earlier chapters covered the @wire decorator, schema imports, and reactive parameters. Here the focus is the result the wire provisions.
What the wire provisions
A wire adapter does not return a value the way a function call does. The wire service calls it, and then sends results to your component whenever they change. Each result is an object with two properties, data and error.
- On success,
dataholds the response anderrorisundefined. - On failure,
errorholds the failure details anddataisundefined. - Before the first response arrives, both are
undefined.
The third state matters. A component that is still waiting looks identical to one that has no data. Do not treat "no data" as "failed".
The wire service can also send a new result later. When a user edits the same record elsewhere on the page, Lightning Data Service updates its shared cache and the wire sends fresh data. Your component sees the change without any code of its own.
Two ways to receive the result
You can wire to a property or to a function. Both receive the same { data, error } shape. They differ in who stores it.
Wiring to a property
When you decorate a property, the wire service assigns the whole result object to it. You read this.account.data and this.account.error.
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);
}
}Before the first response, this.account is an object whose data and error are both undefined. The getters above still run safely, because getFieldValue and getFieldDisplayValue return undefined when given no record.
The template checks each property before it renders anything.
<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>This pattern is the simplest. Use it when the template is the only consumer of the result.
Wiring to a function
When you decorate a method, the wire service calls it with the result object each time a new result arrives. You decide what to store.
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;
}
}
}Use a function when you need to run logic on each result, such as computing a derived value, calling another method, or flattening the error into a string. Note that the function runs for every new result, including repeated results from cache updates.
| Aspect | Property | Function |
|---|---|---|
| What you receive | The `{ data, error }` object, assigned for you | The `{ data, error }` object, passed as an argument |
| Where you read it | `this.account.data` in the template or getters | Wherever you store it inside the method |
| Best for | Direct display | Side effects and derived state |
| Stale data risk | None. The wire replaces the whole object | You must clear old values yourself |
The last row is a frequent source of bugs, covered next.
Clear old values in function wires
In the function example, each branch resets the other value. Without that, a record that loads, then fails after recordId changes, would show the old name next to the new error message. The wire service does not reset your fields for you. Property wires avoid the problem because each new result replaces the whole object.
Reading data safely
Do not read fields directly off data. The response nests values under data.fields.Name.value, and each field may be missing. Use getFieldValue and getFieldDisplayValue, which return undefined instead of throwing when the path is absent.
Also avoid copying data into another property and then mutating it. The object the wire provisions is read-only. Assigning to its properties throws an error in strict mode or fails silently, depending on the context. If you need a changed copy, build a new object.
The shape of error
For getRecord, error is usually an object with a body property, plus status and statusText. The useful text sits in body.message. The shape of body varies. A single failure may give an object with message, while a validation failure may give body.output.errors or body.fieldErrors.
Two guidelines follow.
- Guard the access, as in
error.body && error.body.message. Network failures and client-side errors may not have abody. - Do not assume
erroris always a server response. It may be a JavaScriptError, which hasmessagebut nobody.
A small helper keeps this consistent across components.
export function reduceErrors(error) {
if (!error) {
return [];
}
const errors = Array.isArray(error) ? error : [error];
return errors
.filter((item) => !!item)
.map((item) => {
if (Array.isArray(item.body)) {
return item.body.map((entry) => entry.message);
}
if (item.body && typeof item.body.message === 'string') {
return item.body.message;
}
if (typeof item.message === 'string') {
return item.message;
}
return item.statusText || 'Unknown error';
})
.flat();
}Place it in a shared utility module and import it where you need a message.
Common failures behind the error property
| Cause | What you see | Fix |
|---|---|---|
| The user has no read access to the record | `error` with a not-found or insufficient-access status | Show a message. The component cannot fix permissions |
| A field in `fields` is not visible to the user | The whole request fails | Move the field to `optionalFields` if the component can work without it |
| The record was deleted | `error` on the next refresh | Hide the data and show a message |
| `recordId` is not a valid ID | `error` with a bad-request status | Check the value you pass |
The second row is the reason optionalFields exists. A required field the user cannot see fails the whole wire. An optional field is simply left out of the response.
Waiting for a reactive parameter
When a parameter uses $, the wire does not run until the property has a value. If recordId is undefined, the wire stays in the waiting state and neither data nor error is set. This is normal on the first render of a component whose parent sets the ID later. It is not an error, and your component should render nothing.
Putting the checks together
A template that handles all three states gives the user useful feedback.
<template>
<template lwc:if={account.data}>
<p>Name: {name}</p>
</template>
<template lwc:elseif={account.error}>
<p>The record could not be loaded.</p>
</template>
<template lwc:else>
<p>Loading...</p>
</template>
</template>Using lwc:elseif and lwc:else makes the three states mutually exclusive. The earlier example with two separate lwc:if blocks leaves the waiting state blank.
Edge cases
- Repeated results. A function wire may be called several times for the same record as other components update it. Keep the handler free of side effects that must run once, such as sending an analytics event.
- Partial data. An optional field that the user cannot access is missing from
data.fields.getFieldValuereturnsundefinedfor it. Treatundefinedas "not available", not "empty". - Parameter change. When
recordIdchanges, the previousdatais replaced. For a function wire, you receive a new call. Clear anything derived from the old record. - Display values.
getFieldDisplayValuereturns the formatted string, such as a picklist label or a localized date. It may beundefinedfor fields that have no display value, so fall back togetFieldValuewhen needed.
Exercise
A component uses a function wire on getRecord. A user opens record A, which loads, and then navigates to record B, which the user cannot access. The component still shows the name of record A under the error message. What is the cause, and what is the fix?
Show answer
The function only sets errorMessage in the error branch and never clears name, and the wire service does not reset component fields. Set this.name = undefined in the error branch, and set this.errorMessage = undefined in the data branch, so each result replaces the previous state. Alternatively, wire to a property so each result replaces the whole { data, error } object.
Exercise
Why does get name() { return this.account.data.fields.Name.value; } throw on first render, and what should replace it?
Show answer
Before the first response, this.account.data is undefined, so reading .fields throws a TypeError. Use getFieldValue(this.account.data, NAME_FIELD), which returns undefined when there is no record.