Sub topic 11
Refreshing data after a change
This chapter assumes you can already call an Apex method imperatively, pass parameters, and handle the returned Promise. It covers a different problem. After a DML call succeeds, the data on screen is stale. The component has to decide how to bring it up to date.
Why the screen does not update by itself
Imperative calls are one-shot. The component asks, Apex answers, and the result sits in a field you assigned. Nothing watches the database. When updateEmail finishes, this.contacts still holds the old email until you replace it.
Which refresh tool fits depends on where the displayed data came from:
| Data source | Refresh mechanism |
|---|---|
| Result of an imperative call, stored in a field | Call the read method again, or patch the local copy |
| Result of `@wire` with an Apex method | `refreshApex` with the object the wire delivered |
| Record data shown through Lightning Data Service (`getRecord`, `lightning-record-form`) | `notifyRecordUpdateAvailable` |
| Data owned by a parent or sibling component | An event so the owner refreshes |
Strategy 1: re-run the read after the write
For imperative reads, the simplest approach is to move the loading code into its own method. Call it on the first search and again after every successful write. This is the same pattern the earlier chapters used, extended with a save handler.
import { LightningElement } from 'lwc';
import searchContacts from '@salesforce/apex/ContactController.searchContacts';
import updateEmail from '@salesforce/apex/ContactController.updateEmail';
export default class ContactEditor extends LightningElement {
searchTerm = '';
contacts = [];
errorMessage;
isLoading = false;
handleTermChange(event) {
this.searchTerm = event.target.value;
}
handleSearch() {
return this.loadContacts();
}
async loadContacts() {
this.isLoading = true;
this.errorMessage = undefined;
try {
this.contacts = await searchContacts({ searchTerm: this.searchTerm });
} catch (error) {
this.contacts = [];
this.errorMessage = error?.body?.message || error?.message || 'Unknown error';
} finally {
this.isLoading = false;
}
}
async handleSave(event) {
const contactId = event.currentTarget.dataset.id;
const input = this.template.querySelector(`lightning-input[data-id="${contactId}"]`);
this.errorMessage = undefined;
try {
await updateEmail({ contactId, email: input.value });
await this.loadContacts();
} catch (error) {
this.errorMessage = error?.body?.message || error?.message || 'Unknown error';
}
}
}The order matters. The await on updateEmail ensures the read only starts after the write has committed. If you wrote updateEmail(...) without await and called loadContacts() immediately, the two requests could overlap and the read might return the old row.
This costs two round trips per save. That is usually fine. It also guarantees the screen shows what the database holds, including changes made by triggers, flows, or validation logic that you did not anticipate.
The cacheable trap
searchContacts is marked cacheable=true. Salesforce can serve cacheable results from a client-side cache, so a second imperative call with the same parameters may not return the value you just wrote. If you must read fresh data right after a write, use one of these approaches:
- Expose a second, non-cacheable method for the post-write read.
- Have the write method return the updated records, so no second call is needed.
- Move the display to a wire and use
refreshApex, described below.
Returning the saved data from the write method is often the cleanest fix, because it removes the second round trip entirely.
Strategy 2: update the local copy
If the write method returns the saved record, or you trust the input, you can patch the array in place. LWC tracks reassignment of a field, so build a new array instead of mutating an element.
this.contacts = this.contacts.map((c) =>
c.Id === contactId ? { ...c, Email: newEmail } : c
);This is instant and costs no extra call, but it is an assumption that the server stored exactly what you sent. Use it for simple field edits. Avoid it when server logic can change other fields, or when the change could move the record out of the current search results.
Strategy 3: refreshApex for wired data
Sometimes the list is fed by @wire while the edit happens imperatively. This is a common mix. Reads use the wire, because they are cacheable and reactive. Writes use an imperative call, because DML cannot be cacheable. After the write, tell the wire to re-fetch with refreshApex.
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 WiredContactEditor 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';
}
}
handleTermChange(event) {
this.searchTerm = event.target.value;
}
async handleSave(event) {
const contactId = event.currentTarget.dataset.id;
const input = this.template.querySelector(`lightning-input[data-id="${contactId}"]`);
try {
await updateEmail({ contactId, email: input.value });
await refreshApex(this.wiredResult);
} catch (error) {
this.errorMessage = error?.body?.message || error?.message || 'Unknown error';
}
}
}Two details cause most of the bugs here:
- Keep the whole wire result.
refreshApexneeds the object the wire delivered, the one withdataanderror. If you only storeresult.dataand pass that, nothing refreshes. That is why the handler savesresultbefore destructuring it. - Wire to a function, not a property, when you need the result object. With
@wire(searchContacts, ...) contacts;the property holds{ data, error }and you can passthis.contactstorefreshApex. Either form works. Do not mix them, for example by assigningdatainto a property that you later pass torefreshApex.
refreshApex returns a Promise, so awaiting it lets you hide a spinner after the new data has arrived.
Strategy 4: tell Lightning Data Service
If the component sits beside standard record components, such as a lightning-record-form or another component using getRecord, those components have their own cache. An Apex update goes around that cache. Call notifyRecordUpdateAvailable after the Apex call finishes, so those components re-read the record.
import { notifyRecordUpdateAvailable } from 'lightning/uiRecordApi';
async handleSave(event) {
const contactId = event.currentTarget.dataset.id;
const input = this.template.querySelector(`lightning-input[data-id="${contactId}"]`);
await updateEmail({ contactId, email: input.value });
await notifyRecordUpdateAvailable([{ recordId: contactId }]);
}The argument is an array of objects, each with a recordId. This call refreshes Lightning Data Service consumers. It does not replace your own state. If your component also displays the result of an Apex call, you still need strategy 1, 2, or 3 for that part.
Strategy 5: let the owner refresh
When the editing component is a child and the list lives in a parent, the child should not reach into the parent. Dispatch an event after a successful save and let the parent decide how to refresh.
await updateEmail({ contactId, email });
this.dispatchEvent(new CustomEvent('saved', { detail: { contactId } }));The parent handles saved by calling its own loadContacts() or refreshApex. This keeps each component responsible for its own data.
The full flow
The diagram shows strategy 3, the mixed wire-and-imperative case.
Edge cases and failure modes
- Write failed, read ran anyway. Put the refresh after the
awaitof the write, inside the sametry. If the write throws, the refresh is skipped and the catch block shows the error. - Refresh error hides the write success. If
loadContactsfails after a successful save, a single shared catch block reports a save problem. Use separatetryblocks when the distinction matters to the user. - Stale search term.
loadContactsreadsthis.searchTerm, not the value the user last submitted. If the user edits the input between searching and saving, the refresh uses the new text. Store the submitted term in its own field if that matters. - Row disappears. After an edit, a record may no longer match the filter. A full re-read removes it from the list, while a local patch keeps showing it. Decide which behavior you want.
- Double clicks. Disable the Save button while a write is in flight. Two concurrent writes followed by two refreshes can finish out of order.
Exercise
A component displays contacts from @wire(searchContacts, { searchTerm: '$searchTerm' }) and stores only data in this.contacts. After calling updateEmail imperatively, the developer runs await refreshApex(this.contacts) and the list never updates. What are two likely causes, and how do you fix them?
Show answer
First, refreshApex needs the full object the wire delivered, with data and error, not the unwrapped data array. Store the wire result (for example this.wiredResult = result in a wired function) and call refreshApex(this.wiredResult). Second, the write may not have finished or may have failed: make sure updateEmail is awaited, and that the refresh runs only after it succeeds. If the display is fed by an imperative call instead of a wire, call the read method again, using a non-cacheable method if client-cached results could be stale.
Exercise
Your component edits a Contact with an imperative Apex call, and a lightning-record-form for the same Contact is on the same page. After the save, the form still shows the old email. Which call fixes it, and what argument does it take?
Show answer
Call notifyRecordUpdateAvailable from lightning/uiRecordApi after the Apex call resolves, passing an array of objects with a recordId, for example await notifyRecordUpdateAvailable([{ recordId: contactId }]). This tells Lightning Data Service that the record changed outside its knowledge, so the form re-reads it.