Sub topic 6
Refreshing a function wire by keeping the result
This chapter assumes you can wire a cacheable Apex method to a component, write an @AuraEnabled method, and use async/await. It also assumes you know that refreshApex exists and why cached wire data can go stale. Here you will learn how to refresh a wire that is bound to a function, where you have to do some extra bookkeeping.
Why a function wire needs bookkeeping
A wire can be bound to a property or to a function. With a property, the framework assigns the result object to the property. That object has a data key and an error key. The property already holds what refreshApex needs.
With a function, the framework calls your function with the same result object. What happens to it next is up to you. Most function wires destructure data and error and copy them into your own fields. The result object is then discarded, and nothing is left to give to refreshApex.
refreshApex identifies which wire to refresh by looking at the object the wire provisioned. If you pass anything else, it has no link to the wire and cannot refresh it. So the rule for function wires is:
- Accept the whole result object as the function's parameter.
- Store it in a field, before you do anything else with it.
- Pass that field to
refreshApexlater.
The working pattern
This example uses the Apex controller from the plan. getContacts is cacheable, so it can be wired. updateEmail is not cacheable, because cacheable methods cannot perform DML.
import { LightningElement, api, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import getContacts from '@salesforce/apex/ContactController.getContacts';
import updateEmail from '@salesforce/apex/ContactController.updateEmail';
export default class ContactList extends LightningElement {
@api recordId;
contacts;
error;
wiredContactsResult;
@wire(getContacts, { accountId: '$recordId' })
wiredContacts(result) {
this.wiredContactsResult = result;
const { data, error } = result;
if (data) {
this.contacts = data;
this.error = undefined;
} else if (error) {
this.error = error;
this.contacts = undefined;
}
}
async handleSave(event) {
const { contactId, email } = event.detail;
try {
await updateEmail({ contactId, email });
await refreshApex(this.wiredContactsResult);
} catch (e) {
this.error = e;
}
}
}Three details matter here.
- The parameter is named
result, not{ data, error }. Destructuring in the parameter list would throw the object away before you could store it. - The assignment
this.wiredContactsResult = resultcomes first, before anyif. If you stored the result only inside theif (data)branch, an error result would never be saved, and you could not refresh your way out of an error state. handleSavepassesthis.wiredContactsResult, notthis.contacts.this.contactsholds only the array of records.
What happens during a refresh
The sequence below shows one save followed by a refresh.
The last two steps are the ones people forget. A refresh does not change your existing fields directly. It makes the wire call your function again with a new result object. Your function then does what it always does: it stores the object and copies data into this.contacts. Because the function stores the result on every call, wiredContactsResult always points at the latest object.
refreshApex returns a promise. It resolves after the refreshed data has been provisioned to the wire. Awaiting it lets you run follow-up code, such as closing a spinner or showing a toast, once the new data is in place.
Comparing with a property wire
The same component written with a property wire is much shorter, as the plan's second example shows.
import { LightningElement, api, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import getContacts from '@salesforce/apex/ContactController.getContacts';
import updateEmail from '@salesforce/apex/ContactController.updateEmail';
export default class ContactListSimple extends LightningElement {
@api recordId;
@wire(getContacts, { accountId: '$recordId' })
contacts;
async handleSave(event) {
const { contactId, email } = event.detail;
await updateEmail({ contactId, email });
await refreshApex(this.contacts);
}
}| Concern | Property wire | Function wire |
|---|---|---|
| What the framework gives you | A property holding `{ data, error }` | A call to your function with `{ data, error }` |
| What you pass to `refreshApex` | The property itself | A field where you stored the argument |
| Extra code you write | None | Storing the result, copying `data` and `error` |
| Where you can add logic on arrival | Not directly (use a getter) | Inside the function |
Choose a function wire when you need to react to arriving data, for example to reshape records, set several fields, or fire an event. If you only display the data, a property wire is simpler and has fewer ways to go wrong.
Edge cases
The function can be called without data or error
Your wire function may receive a result in which both data and error are undefined. The if/else if in the example handles this by leaving the fields unchanged. Do not write code that assumes one of the two is always present. Store the object anyway, since it is still the object tied to the wire.
Wrong values that look right
The values below are accepted without any error message, and they do nothing.
// Wrong: this is just the array of records.
await refreshApex(this.contacts);
// Wrong: a copy has no link to the wire.
await refreshApex({ data: this.contacts, error: this.error });
// Right: the object the wire function received.
await refreshApex(this.wiredContactsResult);None of these throw. The refresh silently does nothing, and the screen keeps showing old data. When a function-wire refresh seems to have no effect, check the argument first.
Destructuring in the parameter list
This version looks tidy but cannot be refreshed.
@wire(getContacts, { accountId: '$recordId' })
wiredContacts({ data, error }) {
if (data) {
this.contacts = data;
} else if (error) {
this.error = error;
}
}The function never sees the result object, so it cannot store it. Change the parameter to result and destructure on the next line.
More than one wire
Give every function wire its own stored field. Two wires that share one field overwrite each other, and one of them can never be refreshed.
await Promise.all([
refreshApex(this.wiredContactsResult),
refreshApex(this.wiredCasesResult)
]);Promise.all starts both refreshes at once and rejects if either fails. Use it when the two wires do not depend on each other.
Do not refresh from inside the wire function
Calling refreshApex inside the wire function makes the wire call the function again, which calls refreshApex again. This loops. Trigger refreshes only from user actions, from a completed save, or from an event handler.
The stored object is replaced on every call
Each refresh produces a new result object, and your function stores it. If you keep a copy of the first result in connectedCallback or in a constant, later refreshes will use that stale copy. Always read the field at the moment you call refreshApex, as handleSave does.
Handling errors
The try/catch in handleSave covers both calls, but they fail in different ways.
- If
updateEmailrejects, the data was not saved. Thecatchruns andrefreshApexis skipped, which is correct because nothing changed. - If
refreshApexrejects, the data was saved but the screen could not be updated. The user may need a different message, such as telling them to reload.
If you need to distinguish them, use two blocks.
async handleSave(event) {
const { contactId, email } = event.detail;
try {
await updateEmail({ contactId, email });
} catch (e) {
this.error = e;
return;
}
try {
await refreshApex(this.wiredContactsResult);
} catch (e) {
this.error = e;
}
}The return in the first catch stops the method, so a failed save never reaches the refresh.
Summary of the rules
- Name the parameter of the wire function as a single result object.
- Store the object in a field before any branching.
- Pass the field, not
data, not a copy, torefreshApex. - Await the DML call first, then await the refresh.
- Give each wire its own field.
Exercise
A teammate writes this wire function and says refreshApex has no effect after a save. What are the two problems, and how do you fix them? @wire(getContacts, { accountId: '$recordId' }) wiredContacts({ data, error }) { if (data) { this.contacts = data; } } async handleSave(event) { await updateEmail(event.detail); await refreshApex(this.contacts); }
Show answer
First, the parameter is destructured, so the function never holds the result object and cannot store it. Change it to wiredContacts(result), assign this.wiredContactsResult = result as the first line, then destructure data and error from result. Second, handleSave passes this.contacts, which is only the array of records, so refreshApex has no link to the wire. Pass this.wiredContactsResult instead. Optionally, also handle the error branch so error results are stored and shown.
Exercise
A component has two function wires, one for contacts and one for cases. After saving a contact, you want both lists refreshed in parallel. Write the line that does this, and name what you must have set up in the wire functions for it to work.
Show answer
await Promise.all([refreshApex(this.wiredContactsResult), refreshApex(this.wiredCasesResult)]); Each wire function must accept the whole result object and store it in its own separate field (wiredContactsResult and wiredCasesResult) every time it is called.