Sub topic 9
Refreshing wired data with refreshApex
This chapter assumes you can write a wired Apex call to a property and to a function. You should also know that cacheable=true methods are cached on the client, and that wire results arrive as an object with data and error. Here you will learn how to make a wire fetch fresh data when nothing about its parameters has changed.
Why a wire goes stale
A wire re-runs when a reactive parameter changes. If $recordId stays the same, the wire has no reason to call the server again. It keeps showing the value it already provisioned.
That is a problem after a change the wire cannot see. Suppose a user adds a contact through a separate Apex method. The list on screen was fetched before the insert, so it does not include the new row. The wire is not wrong. It just does not know that the server data moved.
The client cache makes this worse. A cacheable=true method can be answered from the cache without a server round trip. Even if you recreated the request yourself, you could get the old answer back.
refreshApex solves both problems. It tells the wire service to invalidate the cached entry for a wire and fetch the data again, and then it delivers the new result to the same wire.
What refreshApex needs
The function is imported from @salesforce/apex, which is a different module from the one that holds your Apex methods:
import { refreshApex } from '@salesforce/apex';It takes one argument: the value that the wire provisioned. That value is the whole object with data and error, not just data. It returns a promise that resolves when the refreshed result has been delivered.
The argument is the part people most often get wrong. The wire service uses that provisioned object to work out which wire, with which parameters, to refresh. If you pass contacts.data, or a copy of the array, it has nothing to identify the wire with, and the call has no effect.
How you get hold of the object depends on how you wired.
| Wired to | What to pass to refreshApex | Notes |
|---|---|---|
| A property | The property itself, such as `this.contacts` | The property already holds the whole `{ data, error }` object. |
| A function | A value you saved from the function's argument | The function receives the object. You must store it yourself. |
Refreshing a property wire
When you wire to a property, no extra bookkeeping is needed:
import { LightningElement, api, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactListRefresh extends LightningElement {
@api recordId;
@wire(getContacts, { accountId: '$recordId' })
contacts;
handleRefresh() {
return refreshApex(this.contacts);
}
}After the refresh completes, this.contacts is replaced with a new object. The template re-renders because the wired property is reactive.
Refreshing a function wire
When you wire to a function, the function receives the object, and the component has no property that holds it. You have to keep it. This is the example from the topic plan:
import { LightningElement, api, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactRefresh extends LightningElement {
@api recordId;
wiredResult;
rows;
@wire(getContacts, { accountId: '$recordId' })
wiredContacts(result) {
this.wiredResult = result;
if (result.data) {
this.rows = result.data;
}
}
handleRefresh() {
return refreshApex(this.wiredResult);
}
}The function takes the whole result as one parameter instead of destructuring { data, error }. If you destructure in the signature, as in the earlier function-wire example, you lose the original object and have nothing to hand to refreshApex. You can destructure inside the body after saving the whole value, if you prefer.
The function runs again after each refresh. It runs with a new result object each time, so this.wiredResult is overwritten with the latest one. This is correct, and you should not skip it. A later refresh should use the newest object.
The usual flow: change, then refresh
The common reason to refresh is a data change made by a different Apex method. That method cannot be cacheable=true, because it changes data. Cacheable methods must not perform DML.
Here is a method that inserts a contact. It runs in user mode so that object and field permissions apply to the insert, the same way WITH USER_MODE applies them to the query:
public with sharing class ContactEditController {
@AuraEnabled
public static Id addContact(Id accountId, String lastName, String email) {
Contact c = new Contact(
AccountId = accountId,
LastName = lastName,
Email = email
);
insert as user c;
return c.Id;
}
}The component calls it imperatively, waits for it to finish, and then refreshes the wire:
import { LightningElement, api, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import getContacts from '@salesforce/apex/ContactController.getContacts';
import addContact from '@salesforce/apex/ContactEditController.addContact';
export default class ContactAdder extends LightningElement {
@api recordId;
lastName = '';
email = '';
errorMessage;
@wire(getContacts, { accountId: '$recordId' })
contacts;
handleLastName(event) {
this.lastName = event.target.value;
}
handleEmail(event) {
this.email = event.target.value;
}
async handleAdd() {
try {
await addContact({
accountId: this.recordId,
lastName: this.lastName,
email: this.email
});
this.errorMessage = undefined;
await refreshApex(this.contacts);
} catch (error) {
this.errorMessage = error.body ? error.body.message : error.message;
}
}
}<template>
<lightning-input label="Last name" value={lastName} onchange={handleLastName}></lightning-input>
<lightning-input label="Email" type="email" value={email} onchange={handleEmail}></lightning-input>
<lightning-button label="Add contact" onclick={handleAdd}></lightning-button>
<template lwc:if={errorMessage}>
<p>{errorMessage}</p>
</template>
<template lwc:if={contacts.data}>
<ul>
<template for:each={contacts.data} for:item="contact">
<li key={contact.Id}>{contact.Name}</li>
</template>
</ul>
</template>
</template>The order matters. The await on addContact means the insert is committed before the refresh starts. If you call refreshApex without waiting, the refresh can return the data as it was before the insert.
Edge cases and gotchas
Wire data is read-only
The data a wire provisions is frozen. You cannot push a new item into contacts.data to fake an update. Assigning to a field of a row throws an error in strict mode. To change what is shown without a refresh, copy the array first, for example [...result.data, newRow], and store the copy in your own field. Doing so means your screen and the server can drift apart, so prefer a refresh when the data is cheap to fetch.
Refreshing before the first result
If the wire has not provisioned a value yet, because a reactive parameter is still undefined, there is nothing to refresh. For a property wire, this.contacts holds an object with data and error unset. For a function wire, this.wiredResult is undefined. Passing undefined to refreshApex raises an error. Guard the call if the user can trigger it early:
handleRefresh() {
if (!this.wiredResult) {
return undefined;
}
return refreshApex(this.wiredResult);
}A failed refresh arrives as an error
If the server call fails during a refresh, the wire receives an error and data is cleared. Your template or function handles it in the same way as an error on the first load. The promise from refreshApex can still resolve in that case, so check the wired error and do not treat a resolved promise as proof of success.
Imperative results cannot be refreshed
refreshApex only works on values that a wire provisioned. The result of await getContacts(...) from an imperative call is just an array. To update it, call the method again. The next chapter section compares the two styles.
Several wires on one component
Each wire needs its own refreshApex call. Run them together with Promise.all:
await Promise.all([
refreshApex(this.contacts),
refreshApex(this.opportunities)
]);Refreshing from a parent
A child component cannot refresh its parent's wire, because it does not hold the provisioned object. Have the child dispatch a custom event after the change, and let the parent call refreshApex on its own wire.
Quick checklist
- Wire to a property, or save the whole result in a wire function.
- Do the data change in a non-cacheable method and
awaitit. - Pass the saved object, not
data, torefreshApex. - Return or
awaitthe promise so errors and timing are handled. - Read the wired
errorafter the refresh.
Exercise
A component wires getContacts to a function written as wiredContacts({ data, error }), storing data in this.rows. A button handler calls refreshApex(this.rows). The list never updates. Give two reasons this fails and the fix.
Show answer
First, this.rows holds only the data array, but refreshApex needs the whole object the wire provisioned. Second, the function signature destructures the argument, so the component never keeps that object. The fix is to change the signature to wiredContacts(result), save this.wiredResult = result, copy result.data into this.rows when it is present, and call refreshApex(this.wiredResult) in the handler.
Exercise
A user clicks a button that calls a non-cacheable addContact method. The code calls addContact(...) and refreshApex(this.contacts) on consecutive lines, with no await on the first. Sometimes the new contact is missing from the list. Why, and how do you fix it?
Show answer
The refresh can reach the server before the insert has committed, so the wire gets the old rows back. Make the handler async, use await addContact(...), and call await refreshApex(this.contacts) only after it resolves. Wrap both calls in try/catch so that a failed insert skips the refresh and shows the error message.