Sub topic 4
Using refreshApex
This chapter assumes you can wire a cacheable Apex method to a component, read data and error from the result, and use async/await. The earlier chapters covered why cached data goes stale and what a wire provisions. This chapter covers the function that fixes staleness: refreshApex.
What refreshApex does
refreshApex is a function exported by the @salesforce/apex module. It takes the result object that a wire gave you, asks the server for fresh data for the same Apex method and parameters, and updates the wire with the response. Your template or handler then runs again with the new data.
import { refreshApex } from '@salesforce/apex';Three facts define how you use it:
- It takes one argument. The argument is the result object the wire provisioned. It is not the data array and not the Apex method.
- It returns a promise. The promise resolves when the refresh has finished and the wire has the new value. You can
awaitit, so code after theawaitruns against fresh data. - It only works for wired Apex. It refreshes wires of cacheable Apex methods. It does nothing useful for imperative Apex calls, which have no wire to update. It also doesn't cover
getRecordand the other Lightning Data Service wires, which are covered in the alternatives chapter.
| Aspect | Behavior |
|---|---|
| Import | `import { refreshApex } from '@salesforce/apex'` |
| Argument | The object the wire provisioned (`{ data, error }`) |
| Return value | A promise |
| Effect | Re-fetches from the server and provisions a new value to the wire |
| Wrong argument | The call has no effect. You usually get no error either. |
What happens during a refresh
A normal wire read can be answered from the client-side cache. A refresh skips that shortcut. The server is queried again, the cache entry is replaced, and the wire emits the new result.
The wire emits the new value before the promise resolves, so after await refreshApex(...) your component fields already reflect the new data.
The smallest working example
This is the Apex controller from earlier. The read method is cacheable. The update method is not, because a cacheable method cannot modify data.
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;
}
}When the wire is bound to a property, the property holds the result object. You pass the property itself:
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 order matters. The updateEmail call must finish before the refresh starts. If you refresh first, the server returns the old values and the refresh appears to do nothing. Using await on both calls guarantees the order.
The template reads from the same property:
<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>Choosing the argument
The wire hands your component a result object with data and error fields. refreshApex needs that exact object, because the framework uses it to identify which wire and which cache entry to refresh. Passing a part of it, or a copy, breaks that link.
// 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);A copy that looks identical still fails, because the framework recognizes the object it provisioned and not one with the same fields. This mistake is the most common one with refreshApex, and it fails silently.
When the wire is bound to a function instead of a property, the framework calls your function with the result object each time it provisions a value. Nothing stores that object for you. You save it in a field and pass the field later:
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;
}
}
}Note the first line of wiredContacts: it stores result before unpacking it. If you destructure { data, error } as the function parameter instead, you lose the object and have nothing valid to give refreshApex. The next chapters cover both wire styles in more detail.
Refreshing without a save
You don't need DML to use refreshApex. Data can change because of a change made elsewhere, such as a record edited by another user, a flow, or a different component. A refresh button covers that case:
import { LightningElement, api, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactListRefreshable extends LightningElement {
@api recordId;
isRefreshing = false;
@wire(getContacts, { accountId: '$recordId' })
contacts;
async handleRefreshClick() {
this.isRefreshing = true;
try {
await refreshApex(this.contacts);
} finally {
this.isRefreshing = false;
}
}
}The finally block clears the busy flag whether the refresh succeeds or rejects. You can bind isRefreshing to a disabled attribute on the button so users can't start overlapping refreshes.
What refreshApex does not do
- It does not run your DML. The refresh only re-reads. Saving is a separate, non-cacheable Apex call that you make first.
- It does not change the wire's parameters. It re-fetches for the parameters the wire currently has. If
recordIdchanges, the wire re-runs by itself, because'$recordId'is reactive. - It does not guarantee the server data changed. If nothing changed on the server, you get the same values back. The refresh still costs a server round trip, so don't call it in a loop or on a timer without a reason.
- It does not work if the wire never ran. A wire does not run while a reactive parameter is
undefined. In that case there is no result object to refresh, and callingrefreshApexwith anundefinedproperty accomplishes nothing.
Quick diagnostic checklist
If a refresh seems to do nothing, check these in order:
- Did you pass the whole wired result object, with no copy and no
.data? - Was the object stored from the same wire that is on the page now?
- Did the save finish (
await) before the refresh started? - Is the Apex method really the one the wire calls, and is it
cacheable=true? - Did the DML actually change a field that the SOQL query returns?
Items 1 to 3 cover most cases in practice.
Exercise
A component uses @wire(getContacts, { accountId: '$recordId' }) wiredContacts({ data, error }) { ... }, with the result destructured in the function signature. A save handler then calls await refreshApex(this.contacts), where this.contacts is set to data inside the function. The list never updates after saving. What is wrong, and how do you fix it?
Show answer
this.contacts holds only the data array, not the object the wire provisioned, so refreshApex cannot identify the wire and does nothing. Change the function to take the whole result (wiredContacts(result)), store it in a field such as this.wiredContactsResult = result, destructure data and error from it afterward, and call await refreshApex(this.wiredContactsResult).
Exercise
In handleSave, a developer writes refreshApex(this.contacts); await updateEmail({ contactId, email });. The list shows the old email after saving. Give two reasons the code is wrong.
Show answer
The refresh starts before the update finishes, so the server returns the old values. Neither call is awaited in the right order either: the refresh promise is not awaited, so the handler cannot know when the fresh data arrived. The fix is await updateEmail(...) first, then await refreshApex(this.contacts).