Sub topic 10
Refreshing cached results with refreshApex
Prerequisites and goals
This chapter assumes you can already do the following:
- Write an
@AuraEnabled(cacheable=true)Apex method. - Call it from a Lightning web component with
@wire. - Call a non-cacheable method imperatively with
async/await. - Read
error.body.messagefrom a failed Apex call.
By the end you will be able to refresh a wired Apex result after the data changes. You will also know the mistakes that make refreshApex appear to do nothing.
Why cached Apex results go stale
A method marked cacheable=true lets the platform keep its result on the client. When a component asks for the same method with the same parameters, Lightning can answer from that cache without waiting for the server. This is why cacheable methods feel fast.
The cost is that the cache does not know when your data changes. Suppose a component shows a contact list from getContacts, and the user saves a new contact through createContact. The insert succeeds on the server, but the cached getContacts result is still the old list. The wire does not re-run, because none of its reactive parameters changed.
Two rules follow from this:
- A cacheable method cannot perform DML, so the write always goes through a different method.
- Nothing links the write to the cached read. You have to tell the wire to fetch again.
refreshApex is how you tell it.
The refreshApex function
refreshApex is a named export of @salesforce/apex. You pass it the value that the wire service gave you. It asks the server for fresh data, updates the cache, and re-provisions the wire with the new result.
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;
@wire(getContacts, { accountId: '$recordId' })
contacts;
async handleRefresh() {
await refreshApex(this.contacts);
}
}Three details matter here.
- The argument is
this.contacts, which is the whole wire result withdataanderrorproperties. It is notthis.contacts.data. refreshApexreturns a promise. The promise settles when the refresh finishes, so you canawaitit before doing anything that depends on the new data.- The wire does not need to be re-declared. After the refresh,
this.contactsholds the new{ data, error }value and the template re-renders.
What happens during a refresh
The diagram shows the order of events when a component writes a record and then refreshes.
The important point is the order. The refresh must start after the write has completed. If you call refreshApex before the createContact promise resolves, the server may return the list without the new record.
Refreshing after a write
Here is the common case: one component that lists contacts and creates them. It combines the cacheable read from the earlier chapters with the non-cacheable createContact method.
This version wires to a function instead of a property. That gives you a place to handle data and error yourself, and it leads to the most common mistake, covered in the next section.
import { LightningElement, api, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import getContacts from '@salesforce/apex/ContactController.getContacts';
import createContact from '@salesforce/apex/ContactController.createContact';
export default class ContactManager extends LightningElement {
@api recordId;
lastName = '';
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.contacts = [];
this.error = error.body ? error.body.message : error.message;
}
}
handleChange(event) {
this.lastName = event.target.value;
}
async handleSave() {
try {
await createContact({
lastName: this.lastName,
accountId: this.recordId
});
await refreshApex(this.wiredContactsResult);
this.lastName = '';
this.error = undefined;
} catch (error) {
this.error = error.body ? error.body.message : error.message;
}
}
}Both calls sit in one try block. If createContact throws, the AuraHandledException message reaches this.error and the refresh is skipped. If the insert succeeds but the refresh fails, the same handler shows the failure.
Keep the whole result when wiring to a function
When you wire to a function, the wire service calls it with one argument, an object shaped like { data, error }. refreshApex needs that same object. If you only keep data, you have nothing valid to pass.
This is wrong:
@wire(getContacts, { accountId: '$recordId' })
wiredContacts({ data, error }) {
this.contacts = data; // the wrapper object is lost
}
async handleSave() {
await refreshApex(this.contacts); // does not refresh the wire
}The fix is the line this.wiredContactsResult = result; in the earlier example. Store the original argument in its own field, and pass that field to refreshApex. Use a separate field for the data you render.
A property wire avoids this problem, because the property itself is the wire result. A function wire is the better choice when you need to transform the data before showing it.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| The list does not change after a save | `refreshApex` was never called, or it ran before the write finished | `await` the write, then call `refreshApex` |
| `refreshApex` has no effect | You passed `data` or a destructured copy, not the wire result | Pass the property, or store the full `result` argument |
| The refreshed data is still old | You refreshed a different wire than the one rendering the data | Pass the result of the wire that supplies the template |
| Error when you edit the returned array | Wired data is read-only | Copy it first, for example `[...data]` |
| The refresh fails after a successful save | The read method threw, for example because of missing field access | Catch the rejection and display `error.body.message` |
| Nothing refreshes when a parameter changes | You expected `refreshApex` to be needed | Not needed. A changed reactive parameter re-runs the wire by itself |
Refreshing from other components
refreshApex takes a wire result that your own component holds. A sibling or parent component cannot refresh your wire, because it does not have your result object.
When a write happens in one component and the list lives in another, make the list component do its own refresh. Common ways to signal it:
- A custom event from child to parent, where the parent calls a public
@apimethod on the list component. That method callsrefreshApex. - Lightning Message Service for components that are not in a parent-child relationship. The list component subscribes and calls
refreshApexwhen a message arrives.
In both cases the refresh code stays next to the wire it belongs to.
When refreshApex is the wrong tool
refreshApex fits a wired, cacheable method whose data changes because of something the component knows about. Some situations call for a different approach:
- Imperative reads. If you load data by calling a method yourself, call it again. A non-cacheable method always goes to the server.
- Data that changes often. If freshness matters on every view, a non-cacheable method called imperatively is simpler than refreshing a cache that is stale most of the time.
- Changes made by other users.
refreshApexonly runs when your code calls it. It does not push changes from the server. A manual refresh button, a timer, or a platform event handler can trigger it. - Single-record display. For fields on one record, Lightning Data Service wires keep themselves in step with record edits, and you may not need Apex. The choice is covered in a later chapter.
Avoid dropping cacheable=true just to get fresh data. You lose the speed benefit and you can no longer use @wire with the method, because wired methods must be cacheable.
Checking your understanding
Exercise
A component wires getContacts to a function named wiredContacts({ data, error }) and stores this.contacts = data. After saving a contact with an imperative call, refreshApex(this.contacts) does not update the list. Why, and what are two changes that fix it?
Show answer
this.contacts holds only the array from data, not the { data, error } result object that the wire service emitted, so refreshApex has no wire to refresh. Fix 1: change the handler to take the whole result, store it with this.wiredContactsResult = result;, destructure data and error from it, and call refreshApex(this.wiredContactsResult). Fix 2: wire to a property such as @wire(getContacts, { accountId: '$recordId' }) contacts; and call refreshApex(this.contacts). In both cases, await the save before refreshing.
Exercise
In handleSave, a developer writes createContact({ ... }); await refreshApex(this.wiredContactsResult); with no await on the first call. What can go wrong, and how do you fix it?
Show answer
createContact returns a promise, and without await the refresh can start before the insert has committed. The server may then return the old list, so the new contact does not appear. Fix it by writing await createContact({ ... }); so the refresh only runs after the write succeeds. Keeping both calls in one try/catch also means a failed insert skips the refresh and shows the error.
Exercise
Two sibling components are on the same page. One creates contacts, and the other displays the list with a wired getContacts. How should the list refresh after a contact is created?
Show answer
The list component needs to call refreshApex on its own wire result, because only it holds that result. Have the creator publish a signal, either a custom event handled by a common parent that calls an @api method on the list, or a Lightning Message Service message that the list subscribes to. The list's handler then calls await refreshApex(this.contacts).