Sub topic 8
How client-side caching affects wired methods
This chapter assumes you can write a wired Apex call to a property or function, and that you know what @AuraEnabled(cacheable=true) means on the Apex side. Here you will see what the cache does, why wired data can look stale, and which mistakes follow from it.
What the cache stores
When an Apex method is marked cacheable=true, the Lightning Data Service client stores the response in the browser. The cache key is the method plus its parameter values. A later call to the same method with the same parameters can be answered from the cache, without a round trip to the server.
A wire uses this cache automatically. You do not configure it.
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
];
}
}Two components on the same page that wire getContacts with the same accountId share one cache entry. The second component does not trigger a second server call.
Why wired data can look stale
The cache holds a copy of what the server returned at one moment. If a record changes, the cached copy does not change by itself. Suppose a user edits a contact, and your list component still shows the old email address. The cached entry still holds the old value, because nothing told the wire that the data changed.
This surprises developers in three common situations:
- A record is created or updated through another component, such as
lightning-record-form, and your wired list does not change. - A record is changed by an imperative Apex call, and the wire keeps its earlier result.
- Another user changes data on the server, and the current user's browser keeps serving the cached copy.
The fix for the first two is to ask for fresh data explicitly. The next chapter covers refreshApex, which does exactly this. For now, remember that the cache is the reason you need it.
Cache and reactive parameters
Each distinct set of parameter values has its own cache entry. Look at this component.
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;
}If recordId changes from account A to account B, the wire looks up the entry for B. If the user then returns to A, the wire can reuse A's earlier entry. This is fast, but it means the data for A may be older than the data on the server.
Cacheable methods must not change data
The cache is only safe when a method has no side effects. For that reason, a method with cacheable=true cannot perform DML (insert, update, delete). Salesforce rejects it at runtime with an error. A method that modifies data must be a separate @AuraEnabled method without cacheable=true, called imperatively.
Imperative calls and the cache
An imperative call to a cacheable method can also be served from the cache. This is easy to miss, because a call written as await getContacts({ accountId }) looks like a fresh request.
import { LightningElement, api } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactImperative extends LightningElement {
@api recordId;
rows;
errorMessage;
async handleLoad() {
try {
this.rows = await getContacts({ accountId: this.recordId });
this.errorMessage = undefined;
} catch (error) {
this.rows = undefined;
this.errorMessage = error.body ? error.body.message : error.message;
}
}
}If you need a guaranteed fresh read on a user action, there are two options. You can mark the Apex method without cacheable=true and call it imperatively. Or you can keep it cacheable for wires and use refreshApex when you know the data changed.
Common errors
| Symptom | Likely cause | What to do |
|---|---|---|
| List does not show an edit made elsewhere | The wire is serving a cached entry | Call `refreshApex` after the change |
| Error when saving from a cacheable method | DML is not allowed with `cacheable=true` | Move the write to a non-cacheable method |
| Imperative call returns old data | The cacheable method answered from the cache | Use a non-cacheable method or refresh the wire |
| Data differs between two users | Each browser has its own cache | Expect this, and refresh when freshness matters |
Exercise
A component wires a cacheable method getContacts to a property. A user edits a contact in a separate form on the same page, but the wired list still shows the old email. Why does this happen, and what is the general fix?
Show answer
The wire is returning the cached response for the same method and parameters, and nothing has told it the underlying data changed. The fix is to request fresh data with refreshApex, passing the value the wire provisioned.
Exercise
Why can't an @AuraEnabled(cacheable=true) method insert a record, and where should the insert go instead?
Show answer
Cached responses are reused without running the method again, so the method must have no side effects. The insert belongs in a separate @AuraEnabled method without cacheable=true, called imperatively.