Sub topic 7
Why Updates Need a Non-Cacheable Method
This chapter assumes you can write a basic @AuraEnabled Apex method, wire it to a Lightning web component, and use async/await. You should also know that a wired method marked cacheable=true returns data from a client-side cache. The chapter explains why a method that changes data must not be marked cacheable. It also shows how to split a controller so that reads and writes each use the right kind of method.
The rule
The platform enforces one rule:
- A method marked
@AuraEnabled(cacheable=true)must not perform DML. DML means insert, update, upsert, delete, or undelete. - A method that performs DML must be
@AuraEnabledwithoutcacheable=true.
You can't work around the rule by writing the DML some other way. The restriction exists for a reason, and once you see the reason, the way to structure your code follows from it.
Why the platform enforces it
A cacheable method is treated like an HTTP GET request. The platform assumes that calling it has no side effects. Calling it twice with the same parameters should give the same result, and it should leave the database unchanged. Three behaviors depend on that assumption.
The client can skip the server call. When a component asks for data from a cacheable method, the client cache can answer without contacting the server. If the method also ran DML, that DML would run on some calls and silently not run on others. The result would depend on cache state that you can't see.
You don't control when the wire service calls the method. A wired method runs when the component connects. It runs again whenever a reactive parameter changes, and again when refreshApex is called. Two components that wire the same method with the same parameters can share one cached response. DML in that method could run any number of times, at moments you didn't choose.
The platform can reuse and revalidate cached values. A cached response is a snapshot of the data at one moment. Cached values are tied to the parameters, not to a user action such as clicking Save. The platform has no reliable way to tell a save request from a read request, so it keeps the two separate.
Because of these behaviors, the platform rejects DML inside a cacheable method. Apex throws a runtime exception when the DML statement executes. You don't get a compile-time warning, so the failure appears only when the method is called.
What happens if you try anyway
Here is a method that breaks the rule. It is shown only as a counterexample.
public with sharing class BrokenContactController {
// Do not do this. The update statement throws at runtime
// because cacheable methods cannot modify data.
@AuraEnabled(cacheable=true)
public static void updateEmail(Id contactId, String email) {
Contact c = new Contact(Id = contactId, Email = email);
update as user c;
}
}The class compiles and deploys. The failure shows up the first time a component calls the method and the update line runs. The exception reaches the component as an error, and no record changes.
A second failure goes the other way. Suppose you remove cacheable=true and then try to wire the method:
import { LightningElement, wire } from 'lwc';
import updateEmail from '@salesforce/apex/ContactController.updateEmail';
export default class WrongWire extends LightningElement {
// Not valid: only cacheable methods can be wired.
@wire(updateEmail, { contactId: '003000000000001', email: '[email protected]' })
result;
}The wire service accepts only cacheable methods. A non-cacheable method can only be called imperatively, from your own code, at a moment you choose. That fits an update well: a save should run once, when the user asks for it.
Cacheable and non-cacheable methods side by side
| Aspect | `cacheable=true` | Not cacheable |
|---|---|---|
| Purpose | Read data | Change data, or any call with side effects |
| DML allowed | No | Yes |
| Can be wired with `@wire` | Yes | No |
| Can be called imperatively | Yes, and the response may come from the client cache | Yes, and the call always goes to the server |
| Response stored in the client cache | Yes | No |
| Runs when | The platform decides: on connect, on parameter change, on refresh | When your code calls it |
Calling a cacheable method imperatively is allowed, but it still follows cacheable rules. It can't perform DML, and the response may come from the cache. A non-cacheable method bypasses the client cache entirely, so it never returns a stale response. It also never populates the cache, which matters for the next section.
Splitting reads and writes in the controller
The standard pattern is one controller with separate methods for each job. Here is the controller from this tutorial's running example:
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;
}
}getContacts is marked cacheable=true. It only queries, so it is safe to cache and safe to wire. updateEmail has no cacheable attribute. It runs update as user, which performs the DML in user mode so that the running user's object and field permissions apply.
Both methods use user-mode security (WITH USER_MODE and update as user). That is a separate concern from caching, but it matters here for a practical reason. Because the update method is called from client code, you should enforce permissions in Apex rather than trust the component to behave.
Avoid a single method that "queries and then updates." If it has to modify data, it can't be cacheable, so it can't be wired, and you lose the caching benefit for the read part. Two focused methods are easier to reason about, test, and reuse.
How the pieces interact at runtime
The sequence below shows what happens when a user saves a change. The wire has already provided data, and the save goes through the non-cacheable method.
The key detail is the last three steps. The update call doesn't pass through the cache and doesn't invalidate it. After a successful save, the server has the new email, but the wired data in your component still shows the old one. That mismatch is the stale data problem from earlier in this tutorial. The non-cacheable method is the right place for the write, but it doesn't fix staleness by itself.
Calling the update method from the component
You import a non-cacheable method the same way as a cacheable one. The difference is how you use it: call it as a function that returns a promise.
import { LightningElement, api, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
import updateEmail from '@salesforce/apex/ContactController.updateEmail';
export default class ContactListSave extends LightningElement {
@api recordId;
saveError;
@wire(getContacts, { accountId: '$recordId' })
contacts;
async handleSave(event) {
const { contactId, email } = event.detail;
try {
await updateEmail({ contactId, email });
this.saveError = undefined;
// The wired data is still the old snapshot at this point.
// The next chapter step, refreshApex, brings it up to date.
} catch (e) {
this.saveError = e;
}
}
}Three points about this code:
- The wire and the imperative call both come from the same Apex class. They differ only in whether the Apex method is cacheable.
- Parameters are passed as a single object whose keys match the Apex parameter names. The names
contactIdandemailmust match the Apex signature exactly. - The
awaitpauseshandleSaveuntil the server responds. If the DML fails, for example because of a validation rule or missing field permission, the promise rejects and thecatchblock runs.
The next sections of this tutorial add the missing step, calling refreshApex after the save succeeds.
Common mistakes in this area
- Adding
cacheable=trueto make a method wireable, when it also does DML. The DML will throw. Split the method instead. - Trying to wire a non-cacheable method. If you want the data to load automatically and react to parameter changes, the method must be cacheable and read-only.
- Assuming a successful update refreshes wired data. It doesn't. The cache is separate from the database, and the update call doesn't touch it.
- Hiding DML inside a method that looks like a read. A cacheable method that calls a helper which inserts a log record will fail the same way. DML anywhere in the call chain counts.
- Reading errors as strings. Errors from Apex arrive as objects. Inspect them, for example through
e.body.message, instead of assuming a string.
Summary of the design
- Reads that populate the UI belong in cacheable methods, which you wire.
- Writes belong in non-cacheable methods, which you call imperatively when the user acts.
- A write doesn't update the cache. You must refresh the wire yourself after the write succeeds.
Exercise
A teammate adds cacheable=true to an Apex method that queries a Contact and then updates its LastCalledDate__c field, so that they can wire it. What goes wrong, and how should the code be restructured?
Show answer
The update statement throws at runtime, because cacheable methods cannot perform DML. The class still compiles, so the error appears only when the method is called. Split the work into two methods: a read-only @AuraEnabled(cacheable=true) method that returns the Contact, which the component can wire, and a separate @AuraEnabled method without cacheable=true that updates the field, which the component calls imperatively when the change should happen.
Exercise
After a successful await updateEmail(...) call, the list in the component still shows the old email address. Why, and what is missing?
Show answer
The update method is not cacheable, so its call goes straight to the server and doesn't invalidate or change the client cache. The wired data is still the old cached snapshot. The component must refresh the wire, using refreshApex with the original wired result, after the update succeeds.