Sub topic 10
Refreshing When Wire Parameters Are Reactive
This chapter assumes you can already wire a cacheable Apex method, store the wired result object, and call refreshApex after a non-cacheable DML method. It also assumes you are comfortable with async/await. Here you will see what changes when the wire has reactive parameters, meaning parameters written as '$propertyName'.
What reactive parameters do
A wire parameter that starts with $ is reactive. The wire service watches the property it names. When the property changes, the service calls the Apex method again with the new value and provisions the new result to your property or function.
That re-fetch is not a refresh in the refreshApex sense. It happens because the input changed. refreshApex solves a different problem: the inputs are the same, but the data on the server has changed.
| Situation | What triggers the new data | Do you call `refreshApex`? |
|---|---|---|
| A reactive parameter changes value | The wire service, automatically | No |
| A reactive parameter is `undefined` | Nothing. The wire does not call Apex until it has a value | No |
| Parameters are unchanged, but a record was edited | Nothing. The cached value is still served | Yes |
Parameters in the cache key
Cacheable Apex results are stored on the client per method and per set of parameter values. A wire called with searchTerm: 'ann' and a wire called with searchTerm: 'bob' read different cache entries.
This has two consequences.
- When a reactive parameter changes, the wire may be served an existing cache entry for the new values instead of a fresh server response. An entry you looked at earlier can therefore show older data than the server holds.
refreshApexworks on the wire you pass it, which holds the current parameter values. Do not assume it also updates entries cached for other parameter values you used earlier. Treat the refresh as covering what the user sees now.
The diagram shows both behaviors in one session.
A worked example: search with a refresh
The next component shows a contact list filtered by a search term. The term is reactive, so typing changes the data. Saving an email uses a non-cacheable method and then refreshes.
First, the Apex controller. The search method is cacheable and takes two parameters.
public with sharing class ContactSearchController {
@AuraEnabled(cacheable=true)
public static List<Contact> searchContacts(Id accountId, String searchTerm) {
String pattern = '%' + (searchTerm == null ? '' : searchTerm) + '%';
return [
SELECT Id, Name, Email
FROM Contact
WHERE AccountId = :accountId
AND Name LIKE :pattern
WITH USER_MODE
ORDER BY Name
LIMIT 50
];
}
}The pattern value is passed as a bind variable, so the user's text is never concatenated into the query string.
Now the component. Both recordId and searchTerm are reactive parameters. The wire is bound to a function, so the component stores the whole result object each time the wire provisions a value.
import { LightningElement, api, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import searchContacts from '@salesforce/apex/ContactSearchController.searchContacts';
import updateEmail from '@salesforce/apex/ContactController.updateEmail';
export default class ContactSearch extends LightningElement {
@api recordId;
searchTerm = '';
contacts;
error;
wiredResult;
delayTimeout;
@wire(searchContacts, { accountId: '$recordId', searchTerm: '$searchTerm' })
wiredSearch(result) {
this.wiredResult = result;
const { data, error } = result;
if (data) {
this.contacts = data;
this.error = undefined;
} else if (error) {
this.error = error;
this.contacts = undefined;
}
}
handleSearchChange(event) {
const value = event.target.value;
clearTimeout(this.delayTimeout);
this.delayTimeout = setTimeout(() => {
this.searchTerm = value;
}, 300);
}
async handleSave(event) {
const { contactId, email } = event.detail;
try {
await updateEmail({ contactId, email });
} catch (e) {
this.error = e;
return;
}
if (this.wiredResult) {
try {
await refreshApex(this.wiredResult);
} catch (e) {
this.error = e;
}
}
}
}Several details here matter for reactive wires.
handleSearchChangewaits 300 ms after the last keystroke before it assignssearchTerm. Every assignment that changes the value causes a new Apex call, so debouncing keeps the call count down.wiredResultis overwritten on every provision. Each time the term changes, the wire hands you a new result object for the new parameters.handleSavereadsthis.wiredResultwhen it runs, not when the component was created. That read always gets the result for the parameters currently on screen.- The save and the refresh have separate
tryblocks. If the save fails, there is nothing to refresh, so the method returns. If only the refresh fails, the save already succeeded, and the error should say so rather than imply the save failed.
Using a property wire instead
If you do not need to transform the data, you can bind the wire to a property. Reactive parameters work the same way.
import { LightningElement, api, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import searchContacts from '@salesforce/apex/ContactSearchController.searchContacts';
import updateEmail from '@salesforce/apex/ContactController.updateEmail';
export default class ContactSearchSimple extends LightningElement {
@api recordId;
searchTerm = '';
@wire(searchContacts, { accountId: '$recordId', searchTerm: '$searchTerm' })
contacts;
handleSearchChange(event) {
this.searchTerm = event.target.value;
}
async handleSave(event) {
const { contactId, email } = event.detail;
await updateEmail({ contactId, email });
await refreshApex(this.contacts);
}
}The contacts property always holds the latest result object for the current parameters. When the parameters change, the service replaces the object. Passing this.contacts at call time therefore gives refreshApex the right object.
The undefined parameter case
A wire with a reactive parameter does not call Apex while any of its $ parameters is undefined. In the examples above, recordId is undefined for a moment on some pages, until the page supplies it. During that time:
- The wire has not provisioned anything.
- With a property wire,
this.contactsisundefineduntil the first provision, sothis.contacts.datathrows aTypeError. - With a function wire,
this.wiredResultisundefinedbecause the function has not run yet.
This is why handleSave above checks if (this.wiredResult). For a property wire, guard the call the same way.
async handleSave(event) {
const { contactId, email } = event.detail;
await updateEmail({ contactId, email });
if (this.contacts) {
await refreshApex(this.contacts);
}
}A value of null is different from undefined. A null parameter is sent to Apex as null, which is why the Apex method above handles a null searchTerm. Initializing searchTerm to '' avoids the question for this example.
Saves that change which records match
Reactive parameters add one more case. A save can change whether a record matches the current parameters. Suppose the search term is ann and a user edits a contact's name from Ann to Bea. After a refresh, the server no longer returns that contact for the term ann. The row disappears from the list.
That is correct behavior, but it can look like a bug to users. If the list item the user was editing vanishes, consider these options:
- Show a message such as "Saved. This contact no longer matches your search."
- Keep the edited row in local state until the user clears the search.
Neither is a refreshApex feature. Decide this in the UI.
Races between a save and a parameter change
The user can type a new search term while a save is in flight. The sequence is:
handleSavecallsupdateEmail.- The user changes the term, and the wire fetches data for the new term.
updateEmailcompletes, andhandleSavecallsrefreshApex(this.wiredResult).
Because handleSave reads this.wiredResult after await updateEmail, step 3 refreshes whichever result is current, which is the new term. That is the right target. The bug appears when code reads the stored result before the await and keeps it in a local variable.
// Risky: the result is captured before the await, so it may belong to old parameters.
const result = this.wiredResult;
await updateEmail({ contactId, email });
await refreshApex(result);Read the stored result after the save completes.
Common mistakes with reactive wires
| Symptom | Likely cause | Fix |
|---|---|---|
| List does not update after typing | The wire parameter lacks the `$`, so it is sent as the literal string | Write `'$searchTerm'` |
| `refreshApex` seems to do nothing after a save | The component passed `data` or a copy instead of the stored result object | Pass the object the wire provisioned |
| `TypeError` on `this.contacts.data` | A reactive parameter is still `undefined` and the wire has not provisioned | Guard with `if (this.contacts)` |
| Old data appears when returning to an earlier search term | The new parameters matched an existing cache entry | Call `refreshApex` after the term changes, or accept the cache behavior |
| An Apex call fires on every keystroke | The input handler assigns the parameter without a delay | Debounce the assignment |
| Edited row vanishes after refresh | The edit made the record stop matching the parameters | Explain it in the UI |
Summary
- A change to a
$-prefixed parameter makes the wire fetch again. You do not callrefreshApexfor that. refreshApexis for the case where the parameters stay the same and the server data changed.- Cache entries are keyed by method and parameter values. Do not expect
refreshApexto update entries for other parameter values. - Always pass the stored result object, read at the time of the call and not captured earlier.
- Guard against an
undefinedresult while parameters are still missing.
Exercise
A component has @wire(searchContacts, { accountId: '$recordId', searchTerm: '$searchTerm' }) contacts;. A user saves an email change with await updateEmail(...) and then calls await refreshApex(this.contacts.data). The list does not change. What is wrong, and what is the fix?
Show answer
refreshApex needs the object the wire provisioned, which holds both data and error. this.contacts.data is only the array of records, so the call has nothing to link back to the wire. Pass the property itself: await refreshApex(this.contacts);.
Exercise
A save handler runs const result = this.wiredResult; await updateEmail(...); await refreshApex(result);. Explain how this can refresh the wrong data when the wire has reactive parameters, and show the fix.
Show answer
If the user changes a reactive parameter while the save is in flight, the wire provisions a new result object for the new parameters and this.wiredResult is replaced. The local result still points at the old object, so the refresh targets parameters the user has already left. The fix is to read the stored result after the save completes: await updateEmail(...); await refreshApex(this.wiredResult);.
Exercise
A wire has the parameter '$recordId', and recordId is undefined when the component first loads. A save button handler calls refreshApex(this.contacts) on a property wire. Which error can occur, and how do you prevent it?
Show answer
Until the wire provisions its first value, this.contacts is undefined, so code that reads this.contacts.data throws a TypeError, and refreshing an undefined result has no wire to refresh. Guard the call with if (this.contacts) { await refreshApex(this.contacts); }, or keep the save button disabled until the data has loaded.