Sub topic 12
Refreshing record data after changes
This chapter assumes you can already build a screen action or a headless action. That means you know recordId, updateRecord, CloseActionScreenEvent, and toast events from the earlier chapters. It also assumes you have used @wire and basic Apex with @AuraEnabled.
A quick action usually changes a record while the user is looking at that record's page. If the page still shows the old value after the panel closes, users will think the action failed. This chapter explains when the page refreshes by itself and when you must trigger the refresh.
How the page gets its data
Standard record page components, such as the highlights panel and record detail, read data through Lightning Data Service (LDS). LDS keeps a client-side cache of records. Components that use getRecord or other lightning/uiRecordApi wire adapters read from that cache.
When a change goes through LDS, the cache is updated and every subscribed component re-renders. updateRecord is one of those paths. The write goes to the server, and the cache entry for that record is refreshed.
Apex is a different path. LDS cannot see what an @AuraEnabled method did with DML (data manipulation language statements such as update). The cache stays stale until you tell LDS the record changed.
Case 1: updateRecord needs no extra code
The screen action from the earlier chapter saves with updateRecord. After await updateRecord({ fields }) resolves, the record page shows the new description. You only dispatch the toast and CloseActionScreenEvent.
Case 2: Apex DML needs notifyRecordUpdateAvailable
Suppose the action calls Apex because it must set several fields in one transaction or run server logic. The Apex class below is a minimal example.
public with sharing class AccountActions {
@AuraEnabled
public static void markReviewed(Id accountId) {
Account acc = [
SELECT Id
FROM Account
WHERE Id = :accountId
WITH USER_MODE
LIMIT 1
];
acc.Description = 'Reviewed on ' + Date.today().format();
update as user acc;
}
}WITH USER_MODE and update as user make the query and DML respect the running user's field-level security and object permissions. Without them, the class runs in system mode for field access, even with with sharing.
The component calls the method, then tells LDS the record changed with notifyRecordUpdateAvailable. This function is exported by lightning/uiRecordApi. It takes an array of objects, each with a recordId, and returns a promise.
import { LightningElement, api } from 'lwc';
import { CloseActionScreenEvent } from 'lightning/actions';
import { notifyRecordUpdateAvailable } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import markReviewed from '@salesforce/apex/AccountActions.markReviewed';
export default class MarkReviewed extends LightningElement {
@api recordId;
isSaving = false;
async handleSave() {
this.isSaving = true;
try {
await markReviewed({ accountId: this.recordId });
await notifyRecordUpdateAvailable([{ recordId: this.recordId }]);
this.dispatchEvent(new ShowToastEvent({
title: 'Success',
message: 'Account marked as reviewed',
variant: 'success'
}));
this.dispatchEvent(new CloseActionScreenEvent());
} catch (error) {
this.dispatchEvent(new ShowToastEvent({
title: 'Error marking account',
message: error?.body?.message || 'Unknown error',
variant: 'error'
}));
} finally {
this.isSaving = false;
}
}
}Three details in this code matter.
- The notification comes after the Apex call resolves. If you notify first, LDS re-fetches the old data.
- The notification is inside the
tryblock. If Apex throws, nothing changed on the server, so no refresh is needed and the user sees the error toast. - The component awaits the notification before closing the panel. This is optional, but it keeps the sequence predictable: save, refresh, confirm, close.
Refreshing from a headless action
A headless action has no panel, but the refresh logic is identical. Make invoke() async, do the work, and notify LDS.
import { LightningElement, api } from 'lwc';
import { notifyRecordUpdateAvailable } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import markReviewed from '@salesforce/apex/AccountActions.markReviewed';
export default class QuickReview extends LightningElement {
@api recordId;
isRunning = false;
@api async invoke() {
if (this.isRunning) {
return;
}
this.isRunning = true;
try {
await markReviewed({ accountId: this.recordId });
await notifyRecordUpdateAvailable([{ recordId: this.recordId }]);
this.dispatchEvent(new ShowToastEvent({
title: 'Success',
message: 'Account marked as reviewed',
variant: 'success'
}));
} catch (error) {
this.dispatchEvent(new ShowToastEvent({
title: 'Error marking account',
message: error?.body?.message || 'Unknown error',
variant: 'error'
}));
} finally {
this.isRunning = false;
}
}
}The isRunning guard matters here. A headless action has no button you can disable, so a user who clicks twice quickly would start two Apex calls. The guard ignores the second click while the first is in progress. There is no panel to close, so the toast is the only feedback.
Wired Apex data and refreshApex
notifyRecordUpdateAvailable refreshes LDS records. It does not refresh data that you loaded with @wire on an Apex method. A quick action component that shows wired Apex results, for example a list of related items inside the panel, needs refreshApex from @salesforce/apex.
import { wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import getItems from '@salesforce/apex/ItemController.getItems';
// inside the class
@wire(getItems, { accountId: '$recordId' })
wiredItems;
async reload() {
await refreshApex(this.wiredItems);
}Pass the whole value the wire service provisioned, not data. If you destructure the wire result into { data, error }, store the full result in another property first. refreshApex needs the original object to find the cached entry.
Choosing the right refresh mechanism
| Situation | Mechanism | Notes |
|---|---|---|
| Saved with `updateRecord`, `createRecord`, or `deleteRecord` | Nothing extra | LDS updates its own cache. |
| Saved with imperative Apex | `notifyRecordUpdateAvailable` | Pass every changed record Id. |
| Component shows `@wire` Apex results | `refreshApex` | Pass the full wire result. |
| Page components outside LDS must reload | `RefreshEvent` from `lightning/refresh` | Works with components that register a refresh handler. Check release notes for your target and API version. |
RefreshEvent is a broader signal. A component dispatches new RefreshEvent() and the page asks registered components to reload. It is the right tool when the change affects things LDS does not track, such as related lists or custom components that load data with Apex. It costs more than a single-record notification, so do not use it as a default.
Edge cases and pitfalls
- Several records changed. If Apex updates the account and two contacts, pass all three Ids in the array:
[{ recordId: a }, { recordId: c1 }, { recordId: c2 }]. Notifying only the page's record leaves the others stale. - Notifying costs a server call. LDS re-fetches the record. Notify only records that changed, and do it once per save, not once per field.
- Related lists. A related list shows child records that are different LDS records from the page's record. Notifying the parent does not always refresh them. If a related list stays stale after an action that created or deleted children, try notifying the child Ids, then
RefreshEvent. - Closing too early. Closing the panel does not cancel work already started. It does unmount the component. Await the save and notification before you dispatch
CloseActionScreenEvent, or the toast and cleanup may run on a component that is gone. - Failed saves. When
updateRecordor Apex rejects, do not refresh. The server data is unchanged, and a refresh only adds a pointless request. - Aura-style refresh.
$A.get('e.force:refreshView')is Aura only. Do not try to reach it from LWC.
Testing the refresh
With @salesforce/sfdx-lwc-jest, you can assert that your component calls the notification after Apex succeeds. Mock the Apex import with jest.mock('@salesforce/apex/AccountActions.markReviewed', () => ({ default: jest.fn() }), { virtual: true }). Then check that notifyRecordUpdateAvailable was called with the record Id and that it was not called when Apex rejected. Use a recent version of the jest package so the lightning/uiRecordApi stub includes notifyRecordUpdateAvailable.
Exercise
A screen action calls an @AuraEnabled method that updates an Account, then immediately closes the panel with CloseActionScreenEvent. The toast shows success, but the record page still displays the old Description until the user reloads. What is missing, and where should it go?
Show answer
The action changed data through Apex, so LDS does not know the cached record is stale. Add await notifyRecordUpdateAvailable([{ recordId: this.recordId }]), imported from lightning/uiRecordApi. Place it after the Apex call resolves and inside the try block, before the toast and the CloseActionScreenEvent dispatch.
Exercise
A headless action saves with updateRecord only, and the record page already refreshes. A teammate wants to add RefreshEvent "to be safe". Give one reason not to.
Show answer
updateRecord already updates the LDS cache and re-renders wired components, so the extra event adds no benefit. RefreshEvent asks the whole page to reload registered components, which costs extra server requests and can cause visible flicker. Use it only when data outside LDS, such as a related list or Apex-loaded component, must reload.