Sub topic 6
Calling Apex declaratively with @wire
This chapter assumes you can write a basic Apex class with SOQL, build a Lightning web component with a template and decorators, and know that cacheable=true marks an Apex method as read-only. The previous chapters covered how to mark a method and what cacheable means. Here you connect such a method to a component with @wire.
What "declarative" means here
A declarative call describes what data the component needs. The platform decides when to fetch it. You don't write a call at a specific moment. You attach an Apex method to a property or function, and the wire service handles these tasks:
- It calls the method when the component is ready.
- It calls the method again when a reactive parameter changes.
- It serves repeated requests with the same parameters from the client cache.
- It delivers the result to your component as an object with
dataanderror.
The alternative is an imperative call, where your code decides when to run the method. That style is covered in a later chapter. Use @wire when the component only reads data and the data depends on component state.
The requirements
A method can be wired only if it meets all of these conditions:
- It is
staticandpublicorglobal. - It is annotated
@AuraEnabled(cacheable=true). - It performs no DML. A cacheable method that tries to write data fails at runtime.
If you wire a method that is not cacheable, the component fails with an error. The failure appears at runtime in the browser, not at deploy time.
A minimal wired component
This is the controller from earlier chapters.
public with sharing class ContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContacts(Id accountId) {
return [
SELECT Id, Name, Email
FROM Contact
WHERE AccountId = :accountId
WITH USER_MODE
ORDER BY Name
LIMIT 50
];
}
}The component imports the method and wires it to a property.
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;
}Three parts matter here:
- The import path has the form
@salesforce/apex/ClassName.methodName. The imported name is a reference to the method, and you can call it anything. - The second argument to
@wireis an object. Its keys must match the Apex parameter names exactly. A key namedaccountidoraccountdoes not bind toaccountId. - The string
'$recordId'is a reactive reference. The$prefix tells the wire service to read the value from the component'srecordIdproperty, and to rerun the call whenever that value changes.
A reactive reference must be a string that starts with $. Writing { accountId: this.recordId } does not work, because decorator arguments are evaluated before any instance exists.
The shape of the result
When you wire to a property, the platform assigns an object to it. The object always has two fields, and only one is meaningful at a time:
| Field | Meaning |
|---|---|
| `data` | The value the Apex method returned, or `undefined` before the first response or after an error |
| `error` | The error object if the call failed, otherwise `undefined` |
The template reads these fields directly.
<template>
<lightning-card title="Contacts" icon-name="standard:contact">
<template lwc:if={contacts.data}>
<ul class="slds-var-p-around_small">
<template for:each={contacts.data} for:item="contact">
<li key={contact.Id}>{contact.Name}</li>
</template>
</ul>
</template>
<template lwc:elseif={contacts.error}>
<p class="slds-var-p-around_small">Could not load contacts.</p>
</template>
</lightning-card>
</template>An empty result is not an error. If the account has no contacts, data is an empty array. An empty array is truthy in JavaScript, so the first branch renders and shows an empty list. If you want a "no contacts" message, test contacts.data.length separately.
Wiring to a function
When you need to transform the result or run logic when it arrives, wire to a function instead of a property. The function receives the same { data, error } object.
import { LightningElement, api, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactListHandler extends LightningElement {
@api recordId;
rows = [];
errorMessage;
@wire(getContacts, { accountId: '$recordId' })
wiredContacts({ data, error }) {
if (data) {
this.rows = data.map((c) => ({
...c,
label: `${c.Name} (${c.Email ?? 'no email'})`
}));
this.errorMessage = undefined;
} else if (error) {
this.rows = [];
this.errorMessage = error.body ? error.body.message : error.message;
}
}
}The function runs on every provision, whether the result is new data or an error. Always reset the field you are not setting, as the code above does. Otherwise a stale error stays on screen after a later call succeeds.
| Aspect | Wire to a property | Wire to a function |
|---|---|---|
| Template access | `contacts.data`, `contacts.error` | Whatever fields you set |
| Transform results | Needs a getter | Done in the function body |
| `refreshApex` argument | The property | The whole provisioned value, which you must store yourself |
| Typical use | Show the data as returned | Reshape data or react to arrival |
The last row matters for the later chapter on refreshing. If you wire to a function, keep a reference to the full { data, error } value you were given, because refreshApex needs it.
Reactive parameters in practice
Reactivity is the main reason to use @wire. This example reloads contacts whenever the user picks a different account.
import { LightningElement, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class AccountContactBrowser extends LightningElement {
selectedAccountId;
@wire(getContacts, { accountId: '$selectedAccountId' })
contacts;
handleAccountChange(event) {
this.selectedAccountId = event.detail.recordId;
}
}<template>
<lightning-record-picker
label="Account"
object-api-name="Account"
onchange={handleAccountChange}>
</lightning-record-picker>
<template lwc:if={contacts.data}>
<p>{contacts.data.length} contacts found.</p>
</template>
</template>Initially selectedAccountId is undefined. The wire service does not call Apex while a reactive parameter is undefined, so no request goes out with a missing ID. This is a useful guard. It also means contacts.data stays undefined until the user picks a value.
null is different. A parameter whose value is null is sent to Apex as null. If the user clears the picker and the handler sets selectedAccountId to null, the SOQL query runs with AccountId = null. That can return contacts with no account. If that is not what you want, guard in the Apex method or convert null to undefined in the handler.
The next diagram shows what happens on the first load and on a repeat with the same parameters.
Gotchas
The data is read-only
The object in data is frozen. Assigning to a field, or calling sort() or push() on an array from data, throws an error in strict mode. Copy before changing it.
get sortedContacts() {
if (!this.contacts.data) {
return [];
}
return [...this.contacts.data].sort((a, b) => a.Name.localeCompare(b.Name));
}Do not assign to a wired property
The platform owns the wired property. If you write this.contacts = something, you replace the wire's output until the next provision. Keep your own derived state in separate fields or getters.
Do not rely on timing
The wire can provision more than once. A cached value may arrive first, and fresher data may follow. Write the template and handlers to work for any number of provisions. Do not put one-time logic, such as firing an analytics event, inside a wired function.
Cached data can be stale
Because results come from the client cache, a change made elsewhere does not appear automatically. If your component saves a contact through a different path, the wired list stays the same until you refresh it. The chapter on refreshApex covers this.
Wire errors have the same shape as imperative errors
The error value from a wire is the same kind of object an imperative call rejects with. The server message is in error.body.message. Network failures may have no body, so check for it, as the examples do.
Security note
A wired method still runs on the server, so the sharing and permission rules apply to it exactly as to any other Apex. with sharing and WITH USER_MODE in the example above keep results limited to what the running user may see. Client caching does not change this. The cache is per user session, and it holds only what that user's query returned.
When to choose @wire
Use @wire when all of these are true:
- The method only reads data.
- The data depends on component state or a record context, and should update when that state changes.
- You are happy to let the platform decide when to fetch.
Choose an imperative call when you need to control timing, such as loading on a button click, or when the operation writes data.
Exercise
A component has @wire(getContacts, { accountId: '$selectedAccountId' }) contacts; and selectedAccountId is undefined when the component loads. What does the wire service do, and what is the value of contacts.data at that point?
Show answer
The wire service does not call the Apex method while a reactive parameter is undefined. Nothing has been provisioned yet, so contacts.data is undefined, and so is contacts.error. The call runs once selectedAccountId is set to a defined value.
Exercise
Your wired function runs data.sort(...) on the array it receives and throws an error. Why does this happen, and how do you fix it?
Show answer
The array in data is read-only, and sort() changes the array in place. Copy it first, for example [...data].sort(...), and use the copy.
Exercise
You wire getContacts to a function. After a failed call followed by a successful one, the error message is still on screen. What is the likely bug?
Show answer
The function sets the error field when error is present, but never clears it when data arrives. Reset the error field to undefined in the data branch, and reset the data field in the error branch.