Sub topic 1
Recap: Wiring a Cacheable Apex Method
This chapter reviews how a Lightning Web Component (LWC) reads Salesforce data through a wired Apex method. The rest of the tutorial builds on this setup. The pieces to keep in mind are the cacheable=true flag, the reactive parameter, and the shape of the object the wire gives you.
Prerequisites
This chapter assumes you already know the following:
- Basic LWC: templates, decorators such as
@apiand@wire, and the component lifecycle. - Apex basics:
@AuraEnabledmethods and SOQL queries. - JavaScript promises and
async/await. - How to deploy a component and an Apex class to a scratch org or sandbox and put the component on a record page.
You do not need to know refreshApex yet. It comes in later chapters.
What you will take from this chapter
By the end you should be able to:
- Write a cacheable Apex method that a component can wire.
- Wire it to a property and to a function.
- Describe what the wire service provisions and when it provisions it.
- Explain why a cacheable method is a read-only contract.
The Apex side: a cacheable method
A component can only wire an Apex method that is marked @AuraEnabled(cacheable=true). The flag tells the platform that the method is safe to cache on the client because it only reads data. Here is the controller used throughout this tutorial:
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
];
}
@AuraEnabled
public static void updateEmail(Id contactId, String email) {
Contact c = new Contact(Id = contactId, Email = email);
update as user c;
}
}The class has two methods, and they differ in one important way:
| Method | Annotation | Reads or writes | Can be wired |
|---|---|---|---|
| `getContacts` | `@AuraEnabled(cacheable=true)` | Reads | Yes |
| `updateEmail` | `@AuraEnabled` | Writes | No, call it imperatively |
A few details in the code are worth noting:
with sharingandWITH USER_MODEmake the query respect the running user's sharing rules and field-level security. They are not required for caching, but you should use them on any method you expose to the client.update as userruns the DML in user mode, so it enforces object and field permissions.LIMIT 50keeps the payload small. Cached results live in the browser, so smaller results are cheaper to store and send.
A later chapter explains why updateEmail cannot be cacheable. For now, remember that a cacheable method must not change data. The platform rejects cacheable methods that perform DML.
The LWC side: importing and wiring
You import an Apex method into a component with a path of the form @salesforce/apex/ClassName.methodName. The imported name is a function reference you can pass to @wire:
import getContacts from '@salesforce/apex/ContactController.getContacts';The @wire decorator takes two arguments. The first is the imported method. The second is an object of parameters, written as a configuration object whose keys match the Apex parameter names.
A parameter value that starts with $ is reactive. The string '$recordId' means "use the current value of this.recordId, and run the wire again whenever it changes." Without the $, the value is a fixed literal string. 'recordId' would send the text "recordId" to Apex instead of the property's value.
Wiring to a property
The simplest form decorates a property:
import { LightningElement, api, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactListSimple extends LightningElement {
@api recordId;
@wire(getContacts, { accountId: '$recordId' })
contacts;
}The platform assigns an object to this.contacts. That object has two fields: data and error. Only one of them holds a value at any time. Before the first response arrives, both are undefined.
The template reads those fields directly:
<template>
<template lwc:if={contacts.data}>
<template for:each={contacts.data} for:item="contact">
<p key={contact.Id}>{contact.Name}: {contact.Email}</p>
</template>
</template>
<template lwc:if={contacts.error}>
<p>Could not load contacts.</p>
</template>
</template>Use the property form when you only need to display the data and do not need to transform it first.
Wiring to a function
You can also decorate a function. The wire service calls the function each time it has a new result, and passes the same { data, error } object as the argument:
import { LightningElement, api, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactList extends LightningElement {
@api recordId;
contacts;
error;
@wire(getContacts, { accountId: '$recordId' })
wiredContacts(result) {
const { data, error } = result;
if (data) {
this.contacts = data;
this.error = undefined;
} else if (error) {
this.error = error;
this.contacts = undefined;
}
}
}The function form gives you a place to run logic. You can sort, filter, or reshape the data, set a loading flag, or log errors. The cost is that you now store the values yourself. Setting both fields on every call, as above, prevents the template from showing an old error next to new data, or the reverse.
The two forms differ in what your component holds:
| Row | Property wire | Function wire |
|---|---|---|
| What you declare | A property | A method |
| What the platform does | Assigns `{ data, error }` to the property | Calls the method with `{ data, error }` |
| What you keep | The property holds the whole result | Only what you copy out of the argument |
| Good for | Display with no processing | Processing, side effects, extra state |
The last row of the "what you keep" line matters later. In the function form, the object that arrives as result is not saved anywhere unless you save it. The chapters on refreshApex come back to this point.
What the wire service does for you
When the component is connected to the page, the wire service starts the process. The diagram shows the usual sequence.
Four points follow from this sequence:
- The wire runs because the component asked for it, not because your code called anything. You never call
getContacts()yourself. - The cache key is the Apex method plus its parameter values. A different
accountIdis a different cache entry. - When a cached entry exists, the component can get data without a server round trip. That is the performance benefit of
cacheable=true. - When any reactive parameter changes, the wire service repeats the lookup with the new values and provisions a new result.
The cache is the reason this tutorial exists. The next chapter looks at what goes wrong when the cached value no longer matches the database.
The data is read-only
The data that a wire provisions is read-only. If you try to change a record in the array, for example this.contacts.data[0].Email = '[email protected]', the assignment fails. In strict mode it throws a TypeError. The platform does this on purpose, because many components can share the same cached result.
When you need to edit values locally, copy the data first:
const editable = data.map((contact) => ({ ...contact }));Each object is now a shallow copy that you can change. Remember that a local edit does not change the record in Salesforce and does not change the cache.
Common mistakes when wiring
These problems show up often, even in code that looks correct:
- Forgetting
cacheable=true. The component fails to wire the method. Fix it in Apex, then redeploy. - Leaving out the
$. The wire sends a literal string. The query then returns nothing, or Apex throws a type conversion error. - Parameter name mismatch. The key in the configuration object must match the Apex parameter name exactly, here
accountId. A mismatch means the parameter arrives asnull. - Reading
databefore it exists. In JavaScript,this.contacts.data.lengththrows whiledatais stillundefined. Guard the access, or uselwc:ifin the template. - Mutating
data. As described above, copy it first. - Expecting an immediate value. The wire is asynchronous. Code in
connectedCallbackthat reads a wired property will seeundefined.
Where this leads
You now have a working read path: a cacheable Apex method, a reactive wire, and a { data, error } result that the template renders. The next chapter takes this working component and shows how its data can become stale. After that, you will see how to keep and use the wired result object, which is what refreshApex needs.
Exercise
A component declares @wire(getContacts, { accountId: 'recordId' }) contacts; and the list is always empty, even though the account has contacts. What is wrong, and how do you fix it? Also name one reason the Apex method itself might be rejected as a wire target.
Show answer
The parameter value is the plain string 'recordId', so the wire sends the literal text "recordId" to Apex instead of the value of this.recordId. Add the $ prefix to make it reactive: { accountId: '$recordId' }. The Apex method is rejected as a wire target if it is not annotated with @AuraEnabled(cacheable=true), or if it tries to perform DML, which cacheable methods cannot do.
Exercise
You wire getContacts to a function and later want to display the data sorted by email. Where should the sort go, and why should you copy the array first?
Show answer
Put the sort inside the wired function, after you read data, and assign the sorted result to your own field. Copy the array first, for example with [...data].sort(...), because the data provisioned by the wire is read-only and sorting it in place would try to change it.