Sub topic 5
Refreshing a Property Wire
This chapter covers the simplest way to use refreshApex: a wire whose result is stored in a class property. It assumes you can already wire a cacheable Apex method, know that wired data comes from a client-side cache, and know what the result object (data and error) looks like. It also assumes you are comfortable with async/await. The next chapter covers wires bound to functions.
What a property wire is
A wire can be attached to a field or to a function. With a field, the framework assigns the wire's output to that field every time it provisions a value. You don't write any code to receive the data.
@wire(getContacts, { accountId: '$recordId' })
contacts;After the first response arrives, this.contacts holds an object with two keys:
datais the returned records, orundefinedif the call failed or hasn't finished.erroris the error object, orundefinedif the call succeeded or hasn't finished.
The framework creates this object. You never build it, and you shouldn't edit it. The framework replaces the whole object each time it provisions a new value. That is why the property is the right thing to hand to refreshApex.
The rule for property wires
Pass the property itself to refreshApex:
await refreshApex(this.contacts);refreshApex needs to know which wire to re-fetch. It identifies the wire by the object the wire provisioned. That object is the value currently stored in your property, so passing the property tells refreshApex exactly which wire you mean.
Here is the full component from the earlier chapters, reduced to the property form:
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);
}
}The component uses two Apex methods, and only one of them is wired. getContacts is @AuraEnabled(cacheable=true), so you can wire it. updateEmail modifies data, so it can't be cacheable and you call it imperatively. After it succeeds, the cached list is out of date, so you refresh it.
What happens during a refresh
refreshApex returns a promise. When you await it, this happens:
refreshApexfinds the wire that provisioned the object you passed.- It bypasses the client-side cache and calls the server for fresh data.
- It stores the new response in the cache.
- The wire provisions a new result object, and the framework assigns it to your property.
- The promise resolves.
Your property is reassigned to a new object. If the template reads contacts.data, the component re-renders with the new records.
The template
The template reads from the property. It has no state of its own, so nothing needs updating after a refresh.
<template>
<template lwc:if={contacts.data}>
<template for:each={contacts.data} for:item="contact">
<p key={contact.Id}>{contact.Name}: {contact.Email}</p>
</template>
</template>
<template lwc:if={contacts.error}>
<p>Could not load contacts.</p>
</template>
</template>The component re-renders because the framework reassigns contacts. You don't call anything to trigger a render.
Keep in mind that lwc:if={contacts.data} is falsy for an empty array only if you test the array's length. An empty array is truthy in JavaScript, so a successful query that returns no rows still shows the (empty) list branch. If you want an "empty state" message, test contacts.data.length through a getter.
Why the argument matters
The most common mistake is passing something that looks equivalent but isn't the object the wire provisioned. Each of the following fails for a different reason:
// Wrong: refreshApex needs the object the wire provisioned, not a part of it.
await refreshApex(this.contacts.data);
// Wrong: copying the values into your own object loses the link to the wire.
await refreshApex({ data: this.contacts.data, error: this.contacts.error });
// Right: pass the original wired result.
await refreshApex(this.contacts);The first call passes the array of records. The array doesn't identify any wire. The second passes an object with the same shape, but it's a new object that the wire never produced. Both look plausible, and neither has any effect on the wire. The failure is usually silent: no exception, no refresh.
If you need the records, read them from the property (this.contacts.data). If you want to refresh, pass the property.
Don't copy the property before refreshing
A related trap is copying the wired result into another field and refreshing that:
// Fragile
connectedCallback() {
this.snapshot = this.contacts;
}
async handleSave() {
await updateEmail(/* ... */);
await refreshApex(this.snapshot); // may point at an older result
}The wire replaces this.contacts with a new object after each provision. A copy taken earlier still references the older object. Read this.contacts at the moment you call refreshApex, as the working example does.
Refresh only after the save succeeds
Because the two calls are awaited in order, the refresh runs after the save has finished. Without await on updateEmail, the refresh could fetch the old data before the update commits, and you would see the stale value again.
// Wrong: the refresh may run before the save commits.
updateEmail({ contactId, email });
await refreshApex(this.contacts);
// Right: wait for the save first.
await updateEmail({ contactId, email });
await refreshApex(this.contacts);If updateEmail throws, the await rejects and the next line doesn't run. That is usually what you want. Nothing changed on the server, so there is nothing to refresh. The next chapters on error handling cover how to report the failure to the user. For a property wire, you can wrap both calls in one try/catch and store the caught error in a separate property.
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 ContactListWithErrors extends LightningElement {
@api recordId;
saveError;
@wire(getContacts, { accountId: '$recordId' })
contacts;
async handleSave(event) {
const { contactId, email } = event.detail;
this.saveError = undefined;
try {
await updateEmail({ contactId, email });
await refreshApex(this.contacts);
} catch (e) {
this.saveError = e;
}
}
}The separate saveError property matters. Don't write to this.contacts.error. The wire owns that object, and it replaces the object on the next provision.
Reactive parameters
The wire in this chapter uses a reactive parameter, '$recordId'. When recordId changes, the wire re-runs with the new value and provisions a new result. You don't need refreshApex for that.
refreshApex re-runs the wire with its current parameters. It refreshes the data for the same inputs. It doesn't change the inputs. If you need different data, change the reactive property instead.
Refreshing more than one wire
Each wire has its own result, so each needs its own refreshApex call. If a component has two property wires and a save affects both, refresh both:
await Promise.all([
refreshApex(this.contacts),
refreshApex(this.accountSummary)
]);Promise.all runs the refreshes in parallel and rejects if either fails. Use it when the two wires don't depend on each other. If the second refresh needs the first to finish, await them one after the other.
Quick checks when nothing changes
If you call refreshApex(this.contacts) and the UI still shows old data, work through these in order:
| Check | What to look for |
|---|---|
| Argument | Is it the property itself, not `.data`, a copy, or a new object? |
| Await | Did you `await` the save before refreshing? |
| Apex method | Is the wired method `cacheable=true`? A non-cacheable method can't be wired. |
| Server change | Did the save actually change what `getContacts` returns? Check the filters and `LIMIT`. |
| Template | Does it read from the property (`contacts.data`) and not from a stale copy? |
The "Server change" row catches problems that look like caching bugs. If the query has LIMIT 50 and the changed record sorts past the 50th row, a correct refresh still doesn't show it.
Summary of the property-wire pattern
- Bind the wire to a property and let the framework store the result in it.
- Read
dataanderrorfrom that property in the template. - Save with a non-cacheable Apex method, and
awaitit. - Call
await refreshApex(this.property)with the property itself. - Keep save errors in their own property.
Exercise
A component has @wire(getContacts, { accountId: '$recordId' }) contacts;. After an imperative save succeeds, the developer writes await refreshApex(this.contacts.data);. The list does not update, and no error appears. Explain why, and give the corrected line.
Show answer
refreshApex identifies the wire by the result object the wire provisioned, which is the whole value of this.contacts (an object holding data and error). this.contacts.data is only the array of records, so it doesn't identify any wire and the call has no effect. The corrected line is await refreshApex(this.contacts);.
Exercise
Why must handleSave write await updateEmail(...) and not just updateEmail(...) before calling refreshApex? Where should a save error be stored, and why not in this.contacts.error?
Show answer
Without await, the refresh can run before the save commits, so the server returns the old data and the UI looks unchanged. A save error should go in a separate property such as saveError, because the wire owns the this.contacts object and replaces it on the next provision, which would discard anything you wrote into it.