Sub topic 1
Refreshing Cached Data with refreshApex in Lightning Web Components
Prerequisites
This chapter assumes you know LWC templates, decorators, @wire, basic Apex, SOQL, and JavaScript promises.
Recap: Wiring a Cacheable Apex Method
An Apex method used with @wire must be marked @AuraEnabled(cacheable=true). The method must only read data. Salesforce can then store its result in a client-side cache.
public with sharing class ContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContacts(Id accountId) {
return [
SELECT Id, Name, Email
FROM Contact
WHERE AccountId = :accountId
WITH USER_MODE
ORDER BY Name
LIMIT 50
];
}
}The LWC supplies the reactive recordId value as the Apex parameter:
import { LightningElement, api, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactList extends LightningElement {
@api recordId;
@wire(getContacts, { accountId: '$recordId' })
contacts;
}Why Cached Data Goes Stale
The cache improves performance, but it can contain an older result. For example, another component, user, Flow, or Apex transaction might change a Contact after this component loaded its data. The component can continue displaying the cached list until the wire runs again.
What a Wire Gives You: The Result Object
A property wire stores an object with data and error properties:
@wire(getContacts, { accountId: '$recordId' })
contacts;When the request succeeds, contacts.data contains the records. When it fails, contacts.error contains the error. This same object is the wire’s provisioned result.
A function wire receives that result explicitly:
wiredContacts(result) {
this.wiredContactsResult = result;
const { data, error } = result;
}Keep the original result object. Do not keep only data, because refreshApex needs the connection to the wire.
Using refreshApex
Import refreshApex from @salesforce/apex, then pass the stored wired result:
import { refreshApex } from '@salesforce/apex';
async refreshContacts() {
await refreshApex(this.contacts);
}For a function wire, pass the saved wiredContactsResult instead. Passing this.contacts.data is incorrect because it is only the data, not the complete result object.
The returned promise settles after the wire is refreshed. Handle rejection when the refresh can fail.
Exercise
What should a component pass to refreshApex for a property wire?
Show answer
The property containing the original wired result, such as this.contacts, not this.contacts.data.