Sub topic 8
Saving a change, then refreshing
This chapter combines two pieces from earlier chapters: a non-cacheable Apex method that changes data, and refreshApex, which re-fetches wired data. It assumes you can wire a cacheable Apex method, write an @AuraEnabled method with SOQL, and use async/await. It also assumes you know that refreshApex takes the object a wire provisioned.
The problem to solve
A component shows a list of contacts from a wired, cacheable Apex method. The user edits one email address and saves. You must do two things:
- Write the change to the database.
- Make the list show the new value.
The first step cannot go through the wired method. The second step does not happen on its own. Calling a different Apex method does not tell the wire that its cached result is out of date, so the list keeps showing the old email until you ask it to re-fetch.
Two Apex methods with different jobs
The Apex class has one method for reading and one for writing.
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 differences matter:
| Aspect | `getContacts` | `updateEmail` |
|---|---|---|
| Annotation | `@AuraEnabled(cacheable=true)` | `@AuraEnabled` |
| Changes data | No | Yes (`update as user`) |
| Can be wired | Yes | No |
| Result cached on the client | Yes | No |
| How LWC calls it | `@wire` | Imperative call, returns a Promise |
Salesforce requires methods that modify data to be non-cacheable. A cacheable method may be answered from the client cache without a server round trip. If it also wrote data, a cache hit would skip the write. The platform therefore forbids DML in cacheable methods, and the call fails if you try.
WITH USER_MODE and update as user run the query and the update with the current user's field-level security and sharing. If the user cannot edit Email, the update throws an exception. That exception reaches your JavaScript as a rejected Promise, which is why the error handling below matters.
The flow
Order is the main thing to get right. The refresh must start only after the save has finished.
If you call refreshApex before the save finishes, the query can run before the update commits. The refresh then succeeds and returns the old data. await on the first call prevents this.
Version 1: a function wire
A function wire gives you a function that receives the whole result object. To refresh later, keep that object in a field.
import { LightningElement, api, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import getContacts from '@salesforce/apex/ContactController.getContacts';
import updateEmail from '@salesforce/apex/ContactController.updateEmail';
export default class ContactList extends LightningElement {
@api recordId;
contacts;
error;
wiredContactsResult;
@wire(getContacts, { accountId: '$recordId' })
wiredContacts(result) {
this.wiredContactsResult = result;
const { data, error } = result;
if (data) {
this.contacts = data;
this.error = undefined;
} else if (error) {
this.error = error;
this.contacts = undefined;
}
}
async handleSave(event) {
const { contactId, email } = event.detail;
try {
await updateEmail({ contactId, email });
await refreshApex(this.wiredContactsResult);
} catch (e) {
this.error = e;
}
}
}Walk through what happens:
- When the wire provisions a value,
wiredContactsruns. The first line stores the entireresultargument inwiredContactsResult. dataanderrorare then copied into your own fields for the template.- When the user saves,
handleSavereads the values from the event'sdetail. A child component that renders the edit form would dispatch this event. await updateEmail(...)calls Apex imperatively. Parameters go in one object whose keys match the Apex parameter names.await refreshApex(this.wiredContactsResult)re-fetches. The wire callswiredContactsagain with a new result object, and the template re-renders from the updatedcontacts.
The key line is the first one in wiredContacts. The object passed to refreshApex must be the one the wire gave you. Your own contacts field holds only the data part, so it is not enough.
Also note that wiredContactsResult is replaced each time the wire provisions a value. After a refresh, the field points at the newest result, so later refreshes keep working.
Version 2: a property wire
If you do not need to transform the data in JavaScript, bind the wire to a property. The property then holds the whole result object, with data and error as its fields.
import { LightningElement, api, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import getContacts from '@salesforce/apex/ContactController.getContacts';
import updateEmail from '@salesforce/apex/ContactController.updateEmail';
export default class ContactListSimple extends LightningElement {
@api recordId;
@wire(getContacts, { accountId: '$recordId' })
contacts;
async handleSave(event) {
const { contactId, email } = event.detail;
await updateEmail({ contactId, email });
await refreshApex(this.contacts);
}
}The template reads contacts.data and contacts.error 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>Choose between the two versions by what you need:
| Need | Use |
|---|---|
| Show data as it arrives, no processing | Property wire |
| Reshape data, set several fields, or run logic when data arrives | Function wire, with the result stored |
| Smallest amount of code | Property wire |
Passing the right object
The most common mistake is passing a piece of the result instead of the result.
// Wrong: refreshApex needs the object the wire provisioned, not a part of it.
await refreshApex(this.contacts.data);
// Wrong: copying the values into your own object loses the link to the wire.
await refreshApex({ data: this.contacts.data, error: this.contacts.error });
// Right: pass the original wired result.
await refreshApex(this.contacts);refreshApex uses the provisioned object to work out which wire to re-run. A plain array, or a lookalike object you built, carries no such link. The call does not throw. It simply refreshes nothing, so the UI stays stale and nothing in the console tells you why.
Error handling in this flow
Each await can reject, and a rejection from the first one skips the second. This is usually what you want. If the save failed, there is nothing new to fetch, and the user should see the save error.
In the function-wire version, the catch block covers both calls. That keeps the example short but blurs a useful distinction: a failed save means the change was not stored, while a failed refresh means the change was stored but the screen is out of date. The next chapter treats these cases separately. For now, the try/catch ensures neither failure becomes an unhandled Promise rejection.
The property-wire version has no try/catch. If updateEmail rejects, the error escapes handleSave as an unhandled rejection. That is acceptable only in a teaching example. In real code, add the same try/catch and show the error to the user.
What the refresh costs
refreshApex makes a server round trip and re-runs the full query, here up to 50 contacts, even though one field changed. This is the price of the approach. It is simple and always correct, because the displayed data matches what the server returns. For a list of this size, the cost is small.
You can also see a brief moment between the save finishing and the new data arriving. If that gap matters, you can show a spinner while the Promise chain is pending. Set a flag before the first await and clear it in a finally block.
Common problems in this flow
- The list does not change after saving. Check what you pass to
refreshApex. It should be the whole wired result, notdata. - The list changes only after a second save. The refresh probably ran before the first save finished. Look for a missing
awaiton the imperative call. updateEmailcannot be wired or fails with a cacheable error. A method that modifies data must not havecacheable=true. Remove it, then call the method imperatively.- The wire never provisions a value, so there is nothing to refresh. In a function wire, the field holding the result is still
undefined. A reactive parameter such as'$recordId'that is stillundefinedprevents the wire from running at all. - The save succeeds but the user sees nothing wrong, then the data reverts. The update may have been rejected by a validation rule or by permissions. The Promise rejects in that case, so make sure the error is shown to the user.
Exercise
A component uses a function wire, @wire(getContacts, { accountId: '$recordId' }) wiredContacts(result) { ... }, and stores only result.data in a field named contacts. After await updateEmail(...), the developer calls await refreshApex(this.contacts) and the list never updates. What are the two problems, and how do you fix them?
Show answer
The first problem is that this.contacts holds only the data array, not the object the wire provisioned, so refreshApex has no wire to refresh. Fix it by assigning the whole result argument to a field (for example this.wiredContactsResult = result;) inside wiredContacts and calling refreshApex(this.wiredContactsResult). The second problem is the refresh would also need to come after the save finishes, which the await on updateEmail already ensures. If that await is missing, the refresh can run before the update commits and return old data, so keep both await keywords. A related point: updateEmail must be a non-cacheable method, because cacheable methods cannot modify data.