Sub topic 2
Wire adapters and the @wire decorator
This chapter assumes you can read JavaScript modules and promises, and that you know the structure of a Lightning web component: an HTML template, a JavaScript class, and a metadata file. It also assumes you have used @api and know that record pages pass a recordId to a component. The chapter explains what the @wire decorator does, what a wire adapter is, and how a wired component receives its results. Later chapters apply these ideas to getRecord in detail.
What a wire adapter is
A wire adapter is a function that a module exports so components can ask for data declaratively. The component does not call the adapter. It describes what it wants, and the Lightning web components framework connects the component to the adapter and delivers results.
Two parts work together:
- The
@wiredecorator is the JavaScript syntax you put on a property or method. - The wire service is the framework code that creates the adapter, passes it your configuration, and sends each result back to your component.
The adapters in lightning/uiRecordApi, such as getRecord, read through Lightning Data Service. Because of that, the data they provide comes from a shared client-side cache. Two components that wire the same record usually share one cached copy instead of each making a server request.
The module contains both kinds of export, and the distinction matters:
| Export | Kind | How you use it |
|---|---|---|
| `getRecord` | Wire adapter | `@wire(getRecord, config)` |
| `updateRecord` | Imperative function | `await updateRecord(recordInput)` |
| `getFieldValue` | Helper function | Called in a getter or method |
| `getRecordNotifyChange` | Imperative function | Called after server-side changes |
Reading uses a wire adapter. Updating uses an imperative function. You cannot wire updateRecord.
The shape of a wire
The decorator takes two arguments: the adapter, and an optional configuration object. It decorates either a property or a function.
@wire(adapter, { configKey: value })
target;The configuration object holds the parameters the adapter needs. For getRecord, these are recordId, fields, and optionalFields.
You import the adapter by name from its module:
import { LightningElement, api, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';Note that wire itself comes from lwc, while the adapter comes from the module that provides it.
Wiring to a property
When you decorate a property, the wire service assigns each result to that property. The result is an object with two keys, data and error. Only one has a value at a time.
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);
}
}The property account starts out with no data. The wire service replaces it with a new object each time the adapter emits a value. The property is read-only from your component's point of view, so do not assign to it yourself.
Because account is replaced rather than mutated, the template re-renders when a new result arrives. The template reads the result and guards against the empty state:
<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>Checking account.data before reading values matters. Before the first result arrives, both data and error are undefined, and the getters above would be called with undefined.
Wiring to a function
When you decorate a function, the wire service calls it every time a new result arrives. It passes one argument, an object with data and error. This form suits cases where you want to transform the data or store the value and the error message separately.
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 sets both fields on every call. Clearing the other value matters. Without it, an old name would stay on screen after a later error, or an old error would stay after a later success.
Choosing between the two forms
| Concern | Wire to a property | Wire to a function |
|---|---|---|
| Amount of code | Least | More |
| Access to `data` and `error` | Through `property.data` and `property.error` | Through the destructured argument |
| Derived values | Getters computed on read | Computed inside the function |
| Side effects on each result | Not available | Available |
Start with a property. Move to a function when you need to run code on each result, such as setting component state, firing an event, or logging.
When the wire provisions data
The wire service does not run at construction time, and the order of events matters when you debug a component.
- The component is created and its
@apiproperties are set. - The component is connected to the DOM.
- The wire service creates the adapter and sends it the configuration, with
$values resolved from the component. - The adapter returns a result, from the cache or from the server.
- The service assigns the result to the property or calls the function.
- The component re-renders.
Two consequences follow. First, this.account is not populated in the constructor, so do not read wire results there. Second, the adapter can emit more than once. A later change to a parameter, or a change to the cached record, causes a new result.
How the configuration is evaluated
A configuration value that starts with $ is a reactive reference to a property on the component. The wire service reads the property and substitutes its value. When the property changes, the service sends the adapter a new configuration. The next chapters cover this in detail, but the following rules are needed to understand wire behavior now:
- Only a string beginning with
$is treated as a reference. Other values are passed as written. - The reference names a component property. A
$on a nested path, such as'$record.Id', is allowed. A computed expression is not. - If a reactive property is
undefined, the adapter does not run and no result is delivered. This is a feature, not a fault. On a record page,recordIdis set after construction, so the wire waits for it.
@wire(getRecord, { recordId: '$recordId', fields: [NAME_FIELD] })
account;If recordId never receives a value, account stays at its initial state. When a wire seems to do nothing, check the reactive property first.
Properties of the result object
Treat the result object as read-only. The framework freezes record data, so code that tries to change it either throws in strict mode or fails silently. To change a value for display, copy it into a new variable.
get upperName() {
const name = getFieldValue(this.account.data, NAME_FIELD);
return name ? name.toUpperCase() : '';
}The adapter can also return error as an object with a body property that holds server details. Use error.body && error.body.message to avoid a TypeError when the error comes from the network and has no body.
Common mistakes
- Reading a wire result in
connectedCallback. The result is usually not ready yet. Use a getter, or wire to a function. - Assigning to the wired property. The service owns the property. Store derived data in a different property.
- Forgetting the
$prefix.recordId: 'recordId'sends the literal stringrecordId, which is not a valid record ID, so the adapter returns an error. - Wiring
updateRecord. It is an imperative function and must be called from a method. - Mutating
data. The object is read-only. Copy values before changing them. - Assuming one call. The adapter can emit again after the first result, so write code that is safe to run repeatedly.
Review
A wire adapter is an exported function that the wire service calls on behalf of your component. You attach it with @wire(adapter, config) to a property or a function. The service sends results as { data, error }, can send them many times, and waits if a reactive parameter is undefined. The adapters in uiRecordApi read through Lightning Data Service, so they benefit from its shared cache. Updating is a separate imperative call.
Exercise
A component uses @wire(getRecord, { recordId: '$recordId', fields: [NAME_FIELD] }) account;. On a record page, the template shows nothing, and logging this.account in connectedCallback prints undefined. Does this prove the wire is broken? Explain, and name where you would read the value instead.
Show answer
No. The wire service provisions the result after the component connects, and it waits until recordId has a value, so this.account is not populated in connectedCallback. Read the value in a getter used by the template, or wire to a function and handle data and error there, so the code runs each time a result arrives.
Exercise
Your component needs to set a name property and an errorMessage property each time getRecord emits. Should you wire to a property or to a function, and why must the function set both values on every call?
Show answer
Wire to a function, because you need to run code on each result. The function should set both values every time so that a stale value from an earlier result, either an old name after an error or an old error after a success, does not remain.