Sub topic 13
Keeping the Rest of the Page in Sync After a Save
This chapter assumes you can build a form with lightning-record-form or lightning-record-edit-form and handle its onsuccess event. It also assumes you know how @wire and @api work. The question here is what happens to the other components on the page once a record is saved.
What refreshes on its own
Both form components save through Lightning Data Service (LDS). LDS keeps a client-side cache of records. When a form saves a record, LDS updates that cache entry and notifies every component that reads the same record through LDS.
These consumers update automatically, with no code from you:
- Components that use
@wire(getRecord, ...)for the same record ID and fields. - Other
lightning-record-form,lightning-record-view-formandlightning-record-edit-formcomponents showing that record. - Standard components on a Lightning Experience record page, such as the highlights panel, when LDS saved the change.
The wired getRecord data is replaced with a new object. Your template re-renders without any refresh call.
What does not refresh: Apex-backed data
Data returned by Apex does not go through the LDS record cache. A wired Apex method marked cacheable=true keeps its own cached result. Saving a Contact with a form does not tell that result anything has changed. The same applies to related lists you build from SOQL queries.
The fix is refreshApex, imported from @salesforce/apex. It takes the whole object the wire delivered, not just data. You must keep that object when the wire handler runs.
Example: a contact list that updates after creating a contact
The Apex class returns the contacts for an account. The method is cacheable so it can be wired.
public with sharing class ContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContacts(Id accountId) {
return [
SELECT Id, FirstName, LastName, Email
FROM Contact
WHERE AccountId = :accountId
WITH USER_MODE
ORDER BY LastName
LIMIT 50
];
}
}The template shows a create form above the list. The AccountId field is pre-filled from the record page and disabled, so the new contact belongs to the current account.
<template>
<lightning-card title="Contacts">
<div class="slds-p-horizontal_medium">
<lightning-record-edit-form
object-api-name="Contact"
onsuccess={handleSuccess}
onerror={handleError}>
<lightning-messages></lightning-messages>
<lightning-input-field field-name="AccountId" value={recordId} disabled></lightning-input-field>
<lightning-input-field field-name="FirstName"></lightning-input-field>
<lightning-input-field field-name="LastName"></lightning-input-field>
<lightning-button class="slds-m-top_small" type="submit" label="Add contact"></lightning-button>
</lightning-record-edit-form>
<template if:true={contacts}>
<ul class="slds-m-top_medium">
<template for:each={contacts} for:item="c">
<li key={c.Id}>{c.FirstName} {c.LastName}</li>
</template>
</ul>
</template>
</div>
</lightning-card>
</template>The class stores the full wire result in wiredContacts and passes it to refreshApex from onsuccess.
import { LightningElement, api, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class AccountContacts extends LightningElement {
@api recordId;
contacts;
error;
wiredContacts;
@wire(getContacts, { accountId: '$recordId' })
handleContacts(result) {
this.wiredContacts = result;
if (result.data) {
this.contacts = result.data;
this.error = undefined;
} else if (result.error) {
this.error = result.error;
this.contacts = undefined;
}
}
async handleSuccess() {
await refreshApex(this.wiredContacts);
this.dispatchEvent(
new ShowToastEvent({ title: 'Contact added', variant: 'success' })
);
}
handleError(event) {
this.dispatchEvent(
new ShowToastEvent({
title: 'Save failed',
message: event.detail.message,
variant: 'error'
})
);
}
}onsuccess fires only after the server has committed the record, so the re-run query sees the new contact. Do not call refreshApex from onsubmit. At that point nothing has been saved yet, and you would refresh stale data.
Telling LDS that a record changed on the server
The reverse problem also exists. If Apex changes a record, for example a button calls an imperative Apex method that recalculates a field, LDS does not know. A getRecord wire or a record form on the page keeps showing the old value.
notifyRecordUpdateAvailable from lightning/uiRecordApi fixes this. You give it the IDs of the records that changed. LDS then re-fetches them from the server and updates all its consumers.
The example below assumes an Apex method ScoreController.recalculate that updates the Account.
import { LightningElement, api } from 'lwc';
import { notifyRecordUpdateAvailable } from 'lightning/uiRecordApi';
import recalculate from '@salesforce/apex/ScoreController.recalculate';
export default class RecalculateButton extends LightningElement {
@api recordId;
async handleClick() {
await recalculate({ accountId: this.recordId });
await notifyRecordUpdateAvailable([{ recordId: this.recordId }]);
}
}Await the Apex call first. If you notify before the server finishes, LDS fetches the old values and you gain nothing. The older function getRecordNotifyChange does the same job. Prefer notifyRecordUpdateAvailable in new code.
Telling sibling components about a save
Sometimes the component that needs to refresh does not read the same record. An example is a summary panel next to a form that totals contacts. LDS cannot help here. You have three options:
- Custom event to the parent. The form component dispatches a custom event. The parent calls a public method or changes an
@apiproperty on the sibling. - Lightning Message Service. Both components publish and subscribe on a message channel. Use it when the components are not in the same parent-child chain, for example on different regions of a page.
RefreshEvent. On Lightning Experience pages, a component can dispatchRefreshEventfromlightning/refresh. Standard components refresh. Custom components opt in by callingregisterRefreshHandlerandunregisterRefreshHandlerfrom the same module. Check the release notes for the page types and containers you target, because support depends on where the component runs.
A custom event is the simplest option. The form component sends the new ID upward after a save:
handleSuccess(event) {
this.dispatchEvent(
new CustomEvent('contactcreated', {
detail: { id: event.detail.id }
})
);
}The parent template listens with oncontactcreated={handleContactCreated}. In the handler, it calls a public @api refresh() method on the sibling with this.template.querySelector('c-contact-summary').refresh(). Inside that method, the sibling calls refreshApex.
Choosing a refresh mechanism
| Situation | What refreshes on its own | What you must do |
|---|---|---|
| Another component reads the same record with `getRecord` | Yes, through the LDS cache | Nothing |
| A list comes from a cacheable Apex wire | No | Call `refreshApex(wiredResult)` in `onsuccess` |
| Apex changed a record and a form or `getRecord` shows it | No | Await the Apex call, then `notifyRecordUpdateAvailable` |
| A distant component needs to react | No | Lightning Message Service, or `RefreshEvent` where supported |
| A parent and child need to coordinate | No | Custom event up, `@api` method or property down |
Common mistakes
- Refreshing too early. Calling
refreshApexfromonsubmitor before an imperative Apex promise resolves reads data from before the save. - Storing only
data.refreshApexneeds the full wire result, as shown above. - Expecting LDS to track SOQL results. A newly created record changes what a query returns. LDS only tracks records it already knows about, so it cannot add a new row to your list.
- Refreshing with
submit()overrides. If you callsubmit(fields)yourself, as covered in the submit-override chapter,onsuccessstill fires after the save. Put your refresh there, not in theonsubmithandler. - Forgetting that errors skip
onsuccess. If validation or a trigger rejects the save, nothing changed. Do not refresh inonerror. Show the message and leave the data alone. - Over-refreshing. Each
refreshApexis a server call. Refresh only the wires affected by the save.
Verifying it works
To test the contact list, open a record page that contains the component and add a contact. The new name should appear in the list without a browser reload. Then open the browser developer tools and check the Network tab. You should see one call for the Apex refresh after the save. If the list stays stale, check three things in order. First, whether wiredContacts is set. Second, whether refreshApex is awaited inside onsuccess. Third, whether the Apex method really returns the new row, for example whether the sharing rules or LIMIT hide it.
Exercise
A component uses @wire(getRecord, { recordId: '$recordId', fields: [NAME_FIELD] }) to show an Account name. A lightning-record-form on the same page edits that Account. After saving, must you call refreshApex to update the name? Why or why not?
Show answer
No. Both components read the same record through Lightning Data Service. When the form saves, LDS updates its cache and pushes new data to the getRecord wire. refreshApex is only needed for Apex-wired data that LDS does not manage.
Exercise
Your imperative Apex method closeCase updates a Case. A lightning-record-form on the page still shows the old Status after the call resolves. What single call, and in what order, fixes this?
Show answer
Await closeCase(...), then await notifyRecordUpdateAvailable([{ recordId: this.recordId }]) from lightning/uiRecordApi. The notification must come after the Apex call finishes. Otherwise LDS re-fetches the old values.
Exercise
A developer wrote @wire(getContacts, { accountId: '$recordId' }) wiredContacts({ data }) { this.contacts = data; } and calls refreshApex(this.contacts) after a save. The list never updates. What is wrong, and how do you fix it?
Show answer
refreshApex needs the full object the wire provisioned, not the data array. Accept the whole result, store it (for example this.wiredContacts = result), set this.contacts = result.data, and call refreshApex(this.wiredContacts).