Sub topic 3
Handling Errors and Testing refreshApex
Assume you know LWC wires, Apex methods, and JavaScript promises. A save and a refresh are separate asynchronous operations. Handle both operations in the same try block, or give them separate error messages when the UI needs to distinguish them.
Handling errors from the save and the refresh
The DML method can fail because of validation rules, permissions, or invalid data. The refresh can fail because the wired Apex call returns an error. Do not assume that a successful save means the refreshed query succeeded.
async handleSave(event) {
const { contactId, email } = event.detail;
try {
await updateEmail({ contactId, email });
} catch (error) {
this.error = 'The contact could not be saved.';
return;
}
try {
await refreshApex(this.wiredContactsResult);
this.error = undefined;
} catch (error) {
this.error = 'The contact was saved, but the list could not be refreshed.';
}
}Store the complete result supplied to a function wire. For a property wire, pass the property itself.
Refreshing when wire parameters are reactive
A reactive parameter, such as $recordId, causes the wire to run again when its value changes. You usually do not need to call refreshApex for that change.
Call refreshApex when the parameter is unchanged but the underlying records changed. Keep the result object current because a later wire invocation replaces it.
Why a refresh does nothing
Common mistakes include:
- Passing
contacts.datainstead of the complete wired result. - Passing a copied object containing
dataanderror. - Calling
refreshApexbefore the DML promise resolves. - Using a method that is not wired by
@wire. - Forgetting
cacheable=trueon the wired Apex method. - Ignoring the promise returned by
refreshApex.
When to use something other than refreshApex
Use Lightning Data Service APIs when the component uses lightning/ui*Api or record adapters. For example, notifyRecordUpdateAvailable can notify record-based wire adapters after an imperative update. Use local state when the changed value is already known and no server re-query is needed.
Testing a component that uses refreshApex
In Jest, mock the DML method and refreshApex. Test both success and rejection paths. Assert that the DML call finishes before the refresh call, and that a refresh rejection displays the correct message.
Exercise
Why should a function wire store its entire result before calling refreshApex?
Show answer
refreshApex needs the framework-provided result object, which preserves the wire's connection to its data and error state.