Sub topic 5
Read-only methods with cacheable=true
This chapter covers the cacheable=true option on @AuraEnabled. It explains what the option promises, what it forbids, how the client cache behaves, and when to leave it off.
It assumes you can write Apex classes, SOQL queries and DML. It also assumes you know the basics of a Lightning web component (LWC): a template, a JavaScript class and decorators such as @api. It builds on the earlier chapters about the @AuraEnabled annotation, method rules and return types.
What cacheable=true means
@AuraEnabled(cacheable=true) tells the platform that the method only reads data. It makes no changes to the database. For the same inputs, the result can safely be stored and reused.
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 option is a contract, and the platform enforces it. In return you get two things:
- The method can be used with
@wire. A wired Apex method must be cacheable. - Results can be stored in a client-side cache, so repeated requests for the same data avoid a round trip to the server.
If you omit the option, the default is cacheable=false. The method can then do DML, but you can only call it imperatively.
How the client cache works
The cache lives in the browser session. Each entry is keyed by the method and its parameter values. getContacts for account 001A and getContacts for account 001B are separate entries.
When a component asks for data, the platform checks the cache first. A cached entry can be returned immediately. The platform may then still ask the server for a fresh copy and update the component if the data changed.
You should not rely on exactly when that revalidation happens. Design the component so that slightly old data is acceptable, or refresh it explicitly when you know it changed.
Three properties of this cache matter in practice:
- It is per user and per session. One user's cached data is never shown to another user.
- It is keyed by parameters. Change a parameter and you get a different entry.
- Errors are not a valid result. A failed call returns an error to the component and does not give you data to reuse.
What a cacheable method must not do
A cacheable method must not change data. That means no insert, update, delete or upsert, and no equivalent Database methods. If one runs from a component request, the platform rejects the call with an error.
This code looks reasonable but breaks the contract:
public with sharing class VisitController {
@AuraEnabled(cacheable=true)
public static Account getAccountAndLogVisit(Id accountId) {
Account acc = [SELECT Id, Name FROM Account WHERE Id = :accountId WITH USER_MODE];
acc.Description = 'Viewed ' + System.now();
update as user acc; // DML in a cacheable method: not allowed
return acc;
}
}Even without the error, this design would be wrong. A cached result means the method may not run at all on the second request, so the "log" would silently be skipped. Split the work into two methods:
public with sharing class VisitController {
@AuraEnabled(cacheable=true)
public static Account getAccount(Id accountId) {
return [SELECT Id, Name, Description FROM Account WHERE Id = :accountId WITH USER_MODE];
}
@AuraEnabled
public static void logVisit(Id accountId) {
Account acc = new Account(Id = accountId, Description = 'Viewed ' + System.now());
update as user acc;
}
}The read is cacheable and the write is not. The component decides when to call each one.
Cacheable versus non-cacheable
| Aspect | `cacheable=true` | `cacheable=false` (default) |
|---|---|---|
| DML allowed | No | Yes |
| Usable with `@wire` | Yes | No |
| Imperative call | Yes, may return a cached value | Yes, always runs on the server |
| Client caching | Yes, keyed by parameters | No |
| Typical use | Queries, lookups, summaries | Create, update, delete, actions with side effects |
| Risk | Stale data after a change | Extra server round trips |
Using a cacheable method from a component
A cacheable method is the usual choice for data that a component displays when it loads. You import the method and wire it to a property. The '$recordId' string makes the call reactive, so it runs again when recordId changes.
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 contacts property receives an object with data and error fields. The next chapter covers wiring in detail. Here is a minimal template that reads it:
<template>
<template lwc:if={contacts.data}>
<template for:each={contacts.data} for:item="contact">
<p key={contact.Id}>{contact.Name}</p>
</template>
</template>
<template lwc:elseif={contacts.error}>
<p>Could not load contacts.</p>
</template>
</template>You can also call a cacheable method imperatively, for example when a user clicks a search button. The call may return a cached value for parameters you have already used. If you must always get fresh data from the server, use a non-cacheable method for that call.
Wired results are read-only
The objects the platform gives to a wired property are read-only. If you try to change a field on contacts.data[0], JavaScript throws an error in strict mode. Copy the data first:
const editable = this.contacts.data.map((c) => ({ ...c, selected: false }));This copy is also the right place to add UI-only fields such as selected.
Choosing parameters that cache well
Because the cache key includes every parameter, the parameters you choose decide how useful the cache is.
- Pass the smallest set of values the query needs, such as an
Idor a search string. - Avoid parameters that change on every call, such as a timestamp. Each value creates a new entry and nothing is ever reused.
- Keep results small. Use
LIMIT, select only the fields the component displays, and return a wrapper class when you need computed values. - Make the method deterministic. If the result depends on the current time, a random number or hidden server state, the cache will return a result that no longer matches.
A search method shows the pattern. The bind variable :pattern keeps user input out of the query text, so SOQL injection is not possible:
public with sharing class ContactSearchController {
@AuraEnabled(cacheable=true)
public static List<Contact> searchContacts(String searchTerm) {
String pattern = '%' + (searchTerm == null ? '' : searchTerm) + '%';
return [
SELECT Id, Name, Email
FROM Contact
WHERE Name LIKE :pattern
WITH USER_MODE
ORDER BY Name
LIMIT 25
];
}
}Stale data and what to do about it
The main cost of caching is stale data. Suppose the component shows a list from getContacts, and the user then creates a contact with a non-cacheable method. The cache entry for that account still holds the old list. Nothing tells the cache that the data changed, so the new contact may not appear.
You have three options:
- Refresh the wired result explicitly. Call
refreshApexafter the change. A later chapter covers it. - Use a non-cacheable method. This is correct when the data must always be current, but you lose both wiring and caching.
- Use Lightning Data Service for single-record data, where the platform keeps the cache consistent for you.
Also remember that the cache holds data as it was when it was read. If an administrator changes a user's field permissions mid-session, the user may still see a cached value until the entry is refreshed. Security is enforced when the server runs the query, so keep WITH USER_MODE or an equivalent check in every method, cacheable or not.
Common errors
- A DML error on a method you marked cacheable. The method modifies data somewhere in its call chain, including in a helper class or a trigger it fires. Remove the write or split the method.
@wirefails to deploy or run against a method. The method is missingcacheable=true, or it is notstaticandpublicorglobal.- The UI does not show a change you just saved. You are looking at a cached result. Refresh the wired property or re-run the call.
- Mutating wired data throws an error. Copy the data into a new object or array first.
- A method returns different data than expected on the second call. The method depends on something outside its parameters. Add that value as a parameter or make the method non-cacheable.
Exercise
A method named getOrCreateDefaultContact(Id accountId) queries for a contact and inserts one if none exists. A developer marks it cacheable=true so it can be wired. What is wrong, and how would you redesign it?
Show answer
A cacheable method must not perform DML, so the insert makes the call fail. Even if it did not fail, a cached result could skip the method on later calls, so the "create" side effect would be unreliable. Split it into two methods: a cacheable getContacts(Id accountId) that only queries, and a non-cacheable createDefaultContact(Id accountId) that inserts. The component wires the read, and calls the write imperatively when the list is empty, then refreshes the wired result.
Exercise
A component wires getContacts for account 001A. The user switches to account 001B and then back to 001A. Which calls can be served from the client cache, and why?
Show answer
The first call for 001A and the first call for 001B go to the server, because no entry exists for those parameters. When the user returns to 001A, the entry for that method and parameter value can be served from the cache. The cache is keyed by the method plus its parameter values, so each account has its own entry.