Sub topic 2
Refreshing Cached Data with `refreshApex`
Assume you know LWC templates, @wire, Apex methods, SOQL, and JavaScript async/await. This chapter uses both property and function wire forms.
Refreshing a property wire
A property wire stores the provisioned value on the component. That value contains data and error. Pass the property itself to refreshApex, not just its data.
import { LightningElement, api, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactList extends LightningElement {
@api recordId;
@wire(getContacts, { accountId: '$recordId' })
contacts;
async refreshContacts() {
await refreshApex(this.contacts);
}
}After the refresh completes, the wire provisions a new value and the component renders again.
Refreshing a function wire by keeping the result
A function wire receives a result object containing data and error. Save that entire object when the wire runs. Later, pass the saved object to refreshApex.
wiredContactsResult;
@wire(getContacts, { accountId: '$recordId' })
wiredContacts(result) {
this.wiredContactsResult = result;
if (result.data) {
this.contacts = result.data;
} else if (result.error) {
this.error = result.error;
}
}
async refreshContacts() {
await refreshApex(this.wiredContactsResult);
}Why updates need a non-cacheable method
A method marked cacheable=true can be used by a wire, but it must not change database data. Use a separate, non-cacheable Apex method for DML, or data manipulation language.
@AuraEnabled
public static void updateEmail(Id contactId, String email) {
update new Contact(Id = contactId, Email = email);
}Saving a change, then refreshing
Call the update imperatively, wait for it to succeed, and then refresh the wire.
import updateEmail from '@salesforce/apex/ContactController.updateEmail';
async handleSave(event) {
const { contactId, email } = event.detail;
try {
await updateEmail({ contactId, email });
await refreshApex(this.wiredContactsResult);
} catch (error) {
this.error = error;
}
}The catch handles both the DML failure and a refresh failure.
Exercise
What should you pass to refreshApex for a function wire?
Show answer
Pass the original result object received by the wire function, stored in a component property.