Sub topic 11
Refreshing data after a change
This chapter assumes you can already call an Apex method imperatively, handle its Promise, and use @wire with a cacheable method. It covers what to do after a call that changes data, so the screen matches the server again.
Why the UI goes stale
An imperative call to a method like updateEmail changes records on the server. Nothing tells the component that data it loaded earlier is now out of date. A list you read through @wire keeps showing the old values, and so does any array you copied into a field. You have to refresh it yourself.
There are three ways to do that. Which one you use depends on where the displayed data came from.
| Data source | Refresh with |
|---|---|
| Result of `@wire` on a cacheable Apex method | `refreshApex` |
| Result of an imperative call | Call the method again, or update local state |
| Records managed by Lightning Data Service (LDS) | `notifyRecordUpdateAvailable` |
Refreshing wired data with refreshApex
refreshApex is exported from @salesforce/apex. It takes the whole value the wire service gave your handler, not only the data property. So you wire to a function and keep the full result.
import { LightningElement, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import searchContacts from '@salesforce/apex/ContactController.searchContacts';
import updateEmail from '@salesforce/apex/ContactController.updateEmail';
export default class ContactList extends LightningElement {
searchTerm = '';
contacts = [];
errorMessage;
wiredResult;
@wire(searchContacts, { searchTerm: '$searchTerm' })
handleWire(result) {
this.wiredResult = result;
const { data, error } = result;
if (data) {
this.contacts = data;
this.errorMessage = undefined;
} else if (error) {
this.contacts = [];
this.errorMessage = error?.body?.message || 'Unknown error';
}
}
async handleSave(event) {
const { contactId, email } = event.detail;
try {
await updateEmail({ contactId, email });
await refreshApex(this.wiredResult);
} catch (error) {
this.errorMessage = error?.body?.message || error?.message || 'Unknown error';
}
}
}The sequence matters. refreshApex runs only after updateEmail resolves, because the await stops the code until the DML has finished. If the update throws, execution jumps to catch and no refresh happens.
Refreshing imperative results
If the list came from an imperative call, there is no wire result to refresh. Call the same method again, or change the local state yourself.
async handleSave(event) {
const { contactId, email } = event.detail;
try {
await updateEmail({ contactId, email });
this.contacts = await searchContacts({ searchTerm: this.searchTerm });
} catch (error) {
this.errorMessage = error?.body?.message || error?.message || 'Unknown error';
}
}Re-querying costs one more server round trip, but it shows what the server now holds, including changes from triggers or other users. Updating local state saves that round trip:
this.contacts = this.contacts.map((c) =>
c.Id === contactId ? { ...c, Email: email } : c
);Do not assign to a property of an object in the existing array. Build new objects, as above, so the component sees the change.
Records shown by LDS
Components using lightning-record-form or getRecord read from the LDS cache. An Apex update bypasses that cache. Call notifyRecordUpdateAvailable from lightning/uiRecordApi with the changed record Ids, and LDS reloads those records.
import { notifyRecordUpdateAvailable } from 'lightning/uiRecordApi';
await updateEmail({ contactId, email });
await notifyRecordUpdateAvailable([{ recordId: contactId }]);Common mistakes
- Passing
this.wiredResult.datatorefreshApex. It needs the whole result object. - Calling
refreshApexwithoutawaitand then reading data right away. - Marking the DML method
cacheable=true. Salesforce rejects DML in cacheable methods, so the update must stay non-cacheable. - Refreshing before the update finishes, which returns the old rows.
Exercise
A component shows contacts from @wire(searchContacts, { searchTerm: '$searchTerm' }) contacts;. After updateEmail resolves, refreshApex(this.contacts.data) has no effect. What is wrong, and how do you fix it?
Show answer
refreshApex needs the full wire result, not only its data. Pass this.contacts (the object with data and error), or wire to a function that stores the whole result and pass that stored value. Also await the updateEmail call first so the refresh runs after the DML completes.