Sub topic 3
How @wire provisions data
This chapter explains what happens between the @wire line in your component and the moment contacts.data has a value. It assumes you can write a cacheable Apex method and import it into a component, and that you know @api properties and JavaScript destructuring. The wire syntax is covered in the next chapters. This chapter covers the mechanism behind it.
Declaring data versus requesting it
With imperative Apex you write the call yourself: you decide when it runs, you wait for the promise, and you store the result. @wire works the other way. You declare which data the component needs and give it a configuration. The framework decides when to fetch it and delivers the result to a property or function.
Here is the wire from the earlier chapters:
import { LightningElement, api, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactList extends LightningElement {
@api recordId;
@wire(getContacts, { accountId: '$recordId' })
contacts;
}The decorator takes two arguments:
- The adapter is
getContacts. This is the imported Apex method, which the platform treats as a wire adapter. - The configuration is
{ accountId: '$recordId' }. It maps Apex parameter names to values. A string starting with$is a reference to a property on the component.
The property contacts is the target. You never assign to it yourself. The wire service writes to it.
The three parts of the wire service
Three parts take part in every wire:
| Part | Role |
|---|---|
| Your component | Declares the adapter, the configuration, and the target (a property or function). |
| Wire service | Part of the LWC framework. It reads the configuration, resolves `$` references, and calls the adapter. It also delivers whatever the adapter emits to your target. |
| Wire adapter | Does the actual work. For Apex, it checks the client cache, calls the server if needed, and emits a result. |
The adapter for an imported Apex method is created by the platform. You don't write it. The method's name, class, and parameters come from the import path @salesforce/apex/ContactController.getContacts.
The lifecycle of a wire
A wire goes through a fixed sequence, and it helps to know where each step sits relative to your component's lifecycle.
- The component is created. The constructor runs, and the wired target has no value yet.
- The component is inserted into the DOM and
connectedCallbackruns. The wire service connects the adapter. - The wire service builds the configuration object. It replaces each
$reference with the current value of that component property. - If the configuration is usable, the adapter is updated with it. The adapter looks in the cache and calls the server if it has no fresh entry.
- The adapter emits a value of the form
{ data, error }. The wire service writes that value to your target. - If a referenced property changes later, the wire service builds a new configuration and repeats from step 4.
- When the component is removed from the DOM, the adapter is disconnected and stops emitting.
Two consequences follow from this sequence:
- Your component renders at least once before any data arrives. In the first render
contacts.dataisundefined, so your template must handle that state. Thelwc:ifblocks in the earlier chapter do this. - You cannot read wired data in the constructor, and you can't rely on it in
connectedCallback. The result is delivered after the component connects, so use a function target or a getter when you need to react to it.
What the adapter emits
The adapter does not return a bare array of contacts. It emits a plain object with exactly two keys, and only one of them has a value at a time:
- On success,
dataholds the Apex return value anderrorisundefined. - On failure,
errorholds the error anddataisundefined.
Before the first emission, both are undefined. This means data === undefined does not tell you whether the request failed or hasn't finished. If you need to tell "loading" from "empty", check for both properties and for an empty array:
<template>
<template lwc:if={contacts.data}>
<p>Loaded {contacts.data.length} contacts.</p>
</template>
<template lwc:elseif={contacts.error}>
<p>Could not load contacts.</p>
</template>
<template lwc:else>
<p>Loading...</p>
</template>
</template>An empty array is truthy in JavaScript, so lwc:if={contacts.data} is true when the query matched no rows. If you want a special "no contacts" message, test the length separately.
Every emission is a new value
The adapter does not mutate the previous result. Each time it has something to report, it emits a new { data, error } object, and the wire service assigns it to the target. The same applies when the target is a function: the function is called again with the new object.
The practical effect is that the component rerenders because the property was reassigned. It does not rerender because something inside it changed. This matters in two situations:
- The wire can emit more than once. A cached result can arrive first and a fresher one can follow. When a reactive parameter changes, you get a new emission for the new configuration.
- Code that depends on the result should run each time the wire emits, not once. A function target is called for every emission.
The sketch below logs each emission so you can watch the sequence in your browser console:
import { LightningElement, api, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactTrace extends LightningElement {
@api recordId;
@wire(getContacts, { accountId: '$recordId' })
wiredContacts(result) {
// Runs once per emission, not once per component.
console.log('emission', JSON.stringify({
hasData: result.data !== undefined,
hasError: result.error !== undefined
}));
}
}Data is read-only
The wire service gives your component the data in a read-only form. If you try to change a field on a record in contacts.data, or push to the array, the framework throws a TypeError in strict mode, with a message such as "Cannot assign to read only property". This is deliberate. The same object may be shared with other components through the cache, so one component must not be able to change what another one reads.
When you need to change the data, for example to sort rows or add a calculated field, copy it first:
import { LightningElement, api, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactSorted extends LightningElement {
@api recordId;
@wire(getContacts, { accountId: '$recordId' })
contacts;
get sortedRows() {
if (!this.contacts.data) {
return [];
}
// Copy the array and each record before changing anything.
return this.contacts.data
.map((c) => ({ ...c, label: `${c.Name} <${c.Email ?? 'no email'}>` }))
.sort((a, b) => a.Name.localeCompare(b.Name));
}
}map already creates a new array, so sort operates on the copy. If you call sort directly on this.contacts.data, it will throw, because sort changes the array in place.
Why the method must be cacheable
The wire service may call the adapter many times, on connect, on every reactive change, and when it refreshes. The platform can only allow that if repeating a call is safe. A method marked @AuraEnabled(cacheable=true) promises that it only reads data. Salesforce relies on that promise to keep results in the client cache and to call the method again when needed.
For that reason, a method used with @wire must be cacheable. If you wire a method that is not, the component fails to work, and the platform reports that the method must be cacheable. A cacheable method can't perform DML, such as insert, update, or delete. It also can't make changes the user would not expect to be repeated.
Cacheable methods also need to be deterministic enough that a cached result is still useful. If the method returns different data each time for reasons unrelated to its parameters, your component can show stale values. The chapter on client-side caching covers that.
When the wire does not run
The wire service calls the adapter only if the configuration is usable. A wire with a $ reference to a property whose value is undefined is not provisioned. The wire service waits until the property has a value and then makes the first call. This is why the earlier examples work when recordId is not available at the moment the component is created. A page sets @api recordId shortly after creation, and the wire runs once it arrives.
Be careful with null. It is a real value, so it is passed to the Apex method as a null parameter. If your method does not expect null, either guard against it in Apex or set the property to undefined until you are ready.
The next chapters build on this behavior. Reactive parameters change the configuration over time. Function targets let you act on each emission. refreshApex asks the adapter for a new value.
Common mistakes
- Reading
this.contacts.datainconnectedCallbackand expecting a value. The first emission arrives after that point. - Treating
undefineddata as an error. It also means the request hasn't finished or the configuration was incomplete. - Calling
sortorpushon wired arrays instead of copying them first. - Wiring a method that lacks
cacheable=true. - Using a configuration key that does not match the Apex parameter name. The key
accountIdmust match the Apex parameteraccountIdexactly, including case.
Exercise
A component wires an Apex method with @wire(getContacts, { accountId: '$recordId' }) contacts;. In connectedCallback the developer logs this.contacts.data and always sees undefined, even though the template later shows the list. Explain why, and say where the developer should put code that depends on the result.
Show answer
The wire service connects the adapter only after the component is connected, and the adapter emits { data, error } after it checks the cache or gets a server response. That emission arrives after connectedCallback has run, so data is still undefined there. Code that depends on the result should run when the wire emits: either wire to a function, which is called on every emission, or read this.contacts.data in a getter or template expression that the framework re-evaluates when the property is reassigned.
Exercise
A developer wants to show contacts sorted by name and writes get sorted() { return this.contacts.data.sort((a, b) => a.Name.localeCompare(b.Name)); }. The component throws an error once data loads. What are the two problems, and how do you fix them?
Show answer
First, this.contacts.data is undefined before the first emission, so reading .sort on it throws; the getter must return an empty array or other fallback when data is missing. Second, wired data is read-only, and sort changes an array in place, so it throws a TypeError. Copy the array first, for example [...this.contacts.data].sort(...), or use map and then sort.