Sub topic 5
How @wire delivers data to a component
This chapter explains what happens between the @wire decorator in your component and the data your template renders. Once you can describe that path, the test wire adapters in the next chapter make sense. A test adapter replaces one piece of this path and leaves the rest alone.
This chapter assumes you have written LWC components with @wire, imported Apex methods, and used lifecycle hooks. It also assumes you know basic Jest. It contains no tests, so it is a concept chapter.
The three parties in a wire
Every wire involves three parties:
- The component declares what it wants. It names an adapter, gives a configuration object, and says where the result should go.
- The adapter knows how to get that data. It is a small piece of code that the platform provides.
getRecord,getObjectInfo, and every@salesforce/apex/...import are adapters. - The wire service sits between them. It connects the adapter when the component is attached to the DOM and watches the configuration for changes. It passes each value the adapter produces back to the component.
The component never calls the adapter. It declares a request, and the runtime supplies results whenever they are available. This is why wired data is described as provisioned, meaning it is delivered to you instead of fetched by you.
A wired component, end to end
The Apex method must be cacheable to be wired. Without cacheable=true, you can only call it imperatively.
public with sharing class ContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContactList() {
return [SELECT Id, Name FROM Contact WITH SECURITY_ENFORCED LIMIT 50];
}
}The component wires the method to a property:
import { LightningElement, wire } from 'lwc';
import getContactList from '@salesforce/apex/ContactController.getContactList';
export default class ContactList extends LightningElement {
@wire(getContactList)
contacts;
}The template reads the two fields the platform places on contacts:
<template>
<template lwc:if={contacts.data}>
<ul>
<template for:each={contacts.data} for:item="contact">
<li key={contact.Id}>{contact.Name}</li>
</template>
</ul>
</template>
<template lwc:if={contacts.error}>
<p class="error">Could not load contacts.</p>
</template>
</template>You never assign to contacts. The platform assigns it, and the value always has the shape { data, error }. Before the first result arrives, both fields are undefined. After a success, data holds the result and error is undefined. After a failure, it is the other way around.
What the wire service does, step by step
The sequence below shows one wire from attach to first render.
- Construction. The first time the component needs the wire, the platform creates an adapter instance. It passes the adapter a callback for sending values back.
- Connect. When the component is inserted into the DOM, the wire service calls the adapter's
connect()method. This is the adapter's cue that someone is listening. - Update. The wire service calls
update(config)with the current configuration. The adapter starts its work, such as a server request or a cache lookup. - Emit. When the adapter has a value, it calls the callback. The wire service writes
{ data, error }to your property, or calls your method with it. - Re-render. Changing a wired property is a reactive change, so the template re-renders on the next microtask.
- Disconnect. When the component is removed from the DOM, the wire service calls
disconnect(). The adapter stops listening and cleans up.
An adapter is a class with this shape. This sketch is a plain-JavaScript illustration of the contract, not something you register yourself in an org:
class ExampleAdapter {
constructor(dataCallback) {
this.dataCallback = dataCallback;
}
connect() {
// The component is now in the DOM.
}
update(config) {
// Called with the current config, now and again whenever it changes.
this.dataCallback({ data: [], error: undefined });
}
disconnect() {
// The component left the DOM. Release anything you hold.
}
}Steps 2 to 4 happen asynchronously. Even if the adapter answers from a cache, the value does not arrive during the same synchronous block of code that attached the element. Chapter 4 on flushing promises depends on this fact. Remember it now: after attaching a component, its wired data is not there yet.
Wired properties and wired functions
You can place @wire on a property or on a method. The two forms receive the same { data, error } object, and they differ in what happens next.
| Aspect | Wired property | Wired function |
|---|---|---|
| Declaration | `@wire(adapter, config) result;` | `@wire(adapter, config) handler(result) { ... }` |
| What you get | The property holds `{ data, error }` | The method is called with `{ data, error }` |
| Best for | Passing data straight to the template | Transforming data, copying it, setting several fields |
| Called when | The property is replaced on each emit | The method runs on each emit |
Use the function form when you need to reshape the result. This example reads a record and keeps only the account name:
import { LightningElement, wire, api } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
import NAME_FIELD from '@salesforce/schema/Account.Name';
export default class RecordName extends LightningElement {
@api recordId;
name;
error;
@wire(getRecord, { recordId: '$recordId', fields: [NAME_FIELD] })
wiredRecord({ data, error }) {
if (data) {
this.name = data.fields.Name.value;
this.error = undefined;
} else if (error) {
this.error = error;
this.name = undefined;
}
}
}The function can run many times, so it must set every field on every branch. If it did not clear error on success, a stale error would stay on screen after a later successful emit.
Reactive configuration
The configuration object is where a wire becomes reactive. A string value that begins with $ is not a literal. It is a path to a property on the component, and the wire service reads it on each evaluation.
In the example above, '$recordId' means "use the value of this.recordId". When recordId changes, the wire service calls update on the adapter with the new configuration. The adapter fetches again and emits a new value.
Three details matter in practice:
- The
$path is resolved against the component instance. Only properties and getters on the component work, and nested paths such as'$record.id'are allowed. - A non-
$value is fixed when the component is created. Changing a literal later has no effect. - A
$property that isundefinedgenerally means "not ready". Built-in adapters such asgetRecorddo not request data until their required parameters have values. This lets a component wait for a parent to setrecordIdwithout an error.
A common bug follows from this. If a wired component stays empty forever, check whether a reactive parameter is still undefined.
Rules about the provisioned value
The value you receive follows rules that affect both components and tests:
- It is read-only. Wired
datais frozen, so you cannot push to an array or set a field on an object. Copy it first, for example with the spread operator orJSON.parse(JSON.stringify(data)), if you need to modify it. - It is a new object on each emit. A later emit replaces the whole
{ data, error }value. Do not hold onto an old reference expecting it to update. - Cacheable Apex may be served from cache. The first emit can come from the client cache and a second emit can follow with fresh data. A wired function can therefore run more than once for one attach.
dataanderrorare mutually exclusive. Components that checkdatafirst anderrorsecond work correctly under this rule.
Why the test environment can swap the adapter
The path above is the reason wired components are testable without an org. The component only knows two things: the adapter it imported, and the { data, error } it receives. It cannot tell what is behind the adapter.
In a Jest run, the @salesforce/sfdx-lwc-jest package replaces the real adapter with a test adapter. The component code and its template stay untouched. Steps 2 to 4 of the lifecycle still happen, but the test controls step 4. The test decides when to emit, what to emit, and whether the emit is data or an error.
The built-in adapters, such as getRecord, have stubs supplied by the package. Apex imports have no real implementation in Jest, so you must provide one. Both cases are covered in the chapters that follow.
Debugging checklist for a wire that shows nothing
When a wired component renders nothing, work through this list:
- Is the Apex method marked
@AuraEnabled(cacheable=true)? - Is every
$parameter in the configuration set to a real value? - Did you treat
contacts.dataas a promise or call it like a function? It is a plain value. - Are you reading the value before the first emit, while
dataanderrorare bothundefined? - Does your wired function reset the fields it does not set on a given branch?
Item 4 is the most common cause in tests, and the next chapters address it directly.
Exercise
A component has @wire(getRecord, { recordId: '$recordId', fields: [NAME_FIELD] }) wiredRecord; and a public property recordId that a parent sets after the child is attached. Immediately after the child is created, wiredRecord.data and wiredRecord.error are both undefined. Give two separate reasons this is expected, and say what you would see later.
Show answer
First, recordId is still undefined, so the reactive parameter is not ready and getRecord does not request anything yet. Second, even when the parameter is set, the adapter's result is delivered asynchronously, so nothing is emitted in the same synchronous block that attached the component. When the parent sets recordId, the wire service calls update with the new config, the adapter emits, and the wired property is replaced with { data, error: undefined } on success or { data: undefined, error } on failure. The template then re-renders.
Exercise
A wired function sets this.name = data.fields.Name.value when data is present, and does nothing otherwise. After a record change causes an error emit, the old name is still shown. What is wrong, and how do you fix it?
Show answer
The function has no branch for error, so this.name keeps its value from the earlier successful emit. Wired functions run on every emit, and each run must set all the state it owns. Add an else if (error) branch that sets this.error = error and this.name = undefined, and clear this.error in the data branch.