Sub topic 5
Reactive parameters with the $ prefix
This chapter assumes you can write a Lightning Web Component (LWC) with an HTML template, a JavaScript class, and @api properties. It also assumes you know basic Apex and SOQL, and that you have already wired an Apex method to a property. Here you learn how to make a wire re-run when a value in your component changes.
What a reactive parameter is
When you wire an Apex method, you pass a configuration object as the second argument to @wire. Each key in that object matches a parameter of the Apex method. Each value is either a fixed value or a reference to a property of your component.
A string value that starts with $ is a reference to a property of the component class. The wire service reads the property named after the $. The string '$recordId' means "the current value of this.recordId".
import { LightningElement, api, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactList extends LightningElement {
@api recordId;
@wire(getContacts, { accountId: '$recordId' })
contacts;
}Here accountId is the name of the Apex parameter. '$recordId' tells the wire service to read this.recordId and pass it to Apex as accountId. When recordId changes, the wire service calls Apex again with the new value and updates contacts.
The Apex method on the other side is the one from earlier chapters:
public with sharing class ContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContacts(Id accountId) {
return [
SELECT Id, Name, Email
FROM Contact
WHERE AccountId = :accountId
WITH USER_MODE
ORDER BY Name
LIMIT 50
];
}
}The key in the JavaScript configuration (accountId) must match the Apex parameter name exactly, including case. If it does not, the call fails with an error about a missing or unknown parameter.
How the wire service evaluates the configuration
The wire service does more than substitute a value once. It observes the referenced properties and re-evaluates the configuration whenever one of them changes.
- The component is created and connected to the page.
- The wire service reads each
$-prefixed property and builds the parameter object. - If every referenced property is defined, the service calls the adapter (here, the Apex method).
- The result is provisioned to the wired property or function.
- When a referenced property changes, the service goes back to step 2.
The step that surprises people is step 3. The call is only made when all the referenced values are defined. The next section covers this.
The undefined rule
If a referenced property is undefined, the wire service does not call Apex. The wired property keeps its initial state and no error is raised. When the property later gets a value, the call goes ahead.
This behavior is useful. A component placed on a record page does not have recordId at the instant it is created in some situations, and the wire simply waits. You do not need to guard against it.
It also creates a common source of confusion. If your component shows nothing and logs no error, check whether a referenced property is still undefined. Common causes are:
- A misspelled property name in the
$string.'$recordID'reads a property that does not exist, so it is alwaysundefined. - A property that is only set after a user action, such as a search term that starts empty.
- An
@apiproperty that the parent never sets.
Only undefined stops the call. A value of null is passed to Apex as null, and an empty string is passed as an empty string. This difference matters for search boxes, which the next example covers.
Referencing a property you set yourself
The referenced property does not need to be an @api property. Any field of the class that the wire service can observe works. A field in an LWC class is reactive for the purpose of rerendering, and the wire service re-evaluates its configuration when a referenced field changes.
Suppose you want a list that depends on the account the user picks. The component keeps the choice in a field and wires to it.
import { LightningElement, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactPicker extends LightningElement {
selectedAccountId;
@wire(getContacts, { accountId: '$selectedAccountId' })
contacts;
handleChange(event) {
this.selectedAccountId = event.detail.recordId;
}
}Until the user picks an account, selectedAccountId is undefined, so no call is made. After handleChange runs, the wire calls Apex with the chosen Id and contacts.data fills in. Choosing a second account triggers another call.
<template>
<lightning-record-picker
label="Account"
object-api-name="Account"
onchange={handleChange}
></lightning-record-picker>
<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 lwc:elseif={contacts.error}>
<p>Could not load contacts.</p>
</template>
</template>Only top-level properties
The string after $ is a property name on the component. It is not an expression. You can use a dotted path such as '$account.Id' in some wire adapters, but you cannot call functions or combine values inside the string. '$recordId + 1' does not work.
When you need a computed value, make a getter and reference it. A getter on the class is a property as far as the wire service is concerned.
import { LightningElement, api, wire } from 'lwc';
import searchContacts from '@salesforce/apex/ContactSearchController.searchContacts';
export default class ContactSearch extends LightningElement {
@api recordId;
rawTerm = '';
@wire(searchContacts, { accountId: '$recordId', term: '$searchTerm' })
contacts;
get searchTerm() {
const trimmed = this.rawTerm.trim();
return trimmed.length >= 2 ? trimmed : undefined;
}
handleInput(event) {
this.rawTerm = event.target.value;
}
}The getter returns undefined until the user has typed at least two characters. Because undefined stops the call, Apex is not called for empty or one-letter terms. You get a minimum-length rule without any extra code in the handler.
The matching Apex method takes both parameters:
public with sharing class ContactSearchController {
@AuraEnabled(cacheable=true)
public static List<Contact> searchContacts(Id accountId, String term) {
String pattern = '%' + String.escapeSingleQuotes(term) + '%';
return [
SELECT Id, Name, Email
FROM Contact
WHERE AccountId = :accountId
AND Name LIKE :pattern
WITH USER_MODE
ORDER BY Name
LIMIT 50
];
}
}The LIKE filter uses a bind variable, so the value is not concatenated into the query text. escapeSingleQuotes is not needed for a bind variable. The call is harmless here, but you can remove it. The bind variable does the protection.
Mixing fixed and reactive values
A configuration object can hold both kinds of values. Only strings that start with $ are treated as references. Every other value is passed as written.
@wire(getContactsByStatus, { accountId: '$recordId', status: 'Active', maxRows: 25 })
contacts;Here status and maxRows never change. Only accountId is reactive. Apex receives all three on every call.
Avoid mutating wired parameters in the wrong place
The wire service reads the referenced properties. It does not read objects you build yourself and hand over. If you want to pass an object parameter, such as a filter object, there is a rule to remember. The service detects a change by comparing values, and if you mutate the same object in place, it may not see a change.
Reassign the property with a new object instead:
filters = { status: 'Active' };
handleStatusChange(event) {
// Replace the object so the wire service sees a new value.
this.filters = { ...this.filters, status: event.detail.value };
}A wire that references '$filters' re-runs after this assignment. Writing this.filters.status = ... on its own is the pattern to avoid, because it can leave the wire holding stale parameters.
Interaction with caching
Each distinct set of parameter values is a separate cache entry for a cacheable method. If a user moves from account A to account B and back to A, the second visit to A can be served from the client cache without a new server call. The chapter on client-side caching explains how long entries live and how to refresh them. For this chapter, the point is that a re-run triggered by a reactive parameter is not always a network request.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Nothing renders, no error | A referenced property is `undefined` | Log the property, check its spelling, and set it before it is needed |
| Error about a missing parameter | The key in the configuration object does not match the Apex parameter name | Match the name and case exactly |
| Wire never re-runs after a change | The referenced object was mutated in place | Assign a new object or value |
| Apex receives the literal text `$recordId` | The `$` was left out of a value you meant to be reactive, or the string was built by concatenation | Use a plain `'$name'` string with nothing else in it |
| Wire runs on every keystroke | The reactive property is the raw input value | Reference a getter or a debounced field instead |
| Apex returns all records for an empty term | The empty string passed the `undefined` check | Return `undefined` from a getter for empty input |
Reducing calls while the user types
A reactive wire re-runs on each change. For a text input, that is a call per keystroke. Cacheable calls are cheap when cached, but each new term is still a server round trip.
A common fix is a debounce. The component copies the typed value into a second field only after the user pauses. The wire references the second field.
import { LightningElement, api, wire } from 'lwc';
import searchContacts from '@salesforce/apex/ContactSearchController.searchContacts';
const DELAY_MS = 300;
export default class ContactSearchDebounced extends LightningElement {
@api recordId;
searchTerm;
timeoutId;
@wire(searchContacts, { accountId: '$recordId', term: '$searchTerm' })
contacts;
handleInput(event) {
const value = event.target.value.trim();
window.clearTimeout(this.timeoutId);
this.timeoutId = window.setTimeout(() => {
this.searchTerm = value.length >= 2 ? value : undefined;
}, DELAY_MS);
}
disconnectedCallback() {
window.clearTimeout(this.timeoutId);
}
}Each keystroke cancels the pending timer and starts a new one. searchTerm changes only after 300 milliseconds without typing, so the wire runs once per pause. The disconnectedCallback clears any pending timer when the component is removed.
One side effect: when the term becomes undefined again, the wire stops calling Apex but contacts.data keeps the previous result. If you want the list to clear, check searchTerm in your template or getter before showing the data.
Reactive parameters and wiring to a function
Everything in this chapter applies the same way when you wire to a function. The configuration object works identically. Only the target differs.
@wire(getContacts, { accountId: '$recordId' })
wiredContacts({ data, error }) {
if (data) {
this.rows = data;
this.errorMessage = undefined;
} else if (error) {
this.rows = undefined;
this.errorMessage = error.body ? error.body.message : error.message;
}
}The function is called each time a new result arrives, including after a parameter change. Because the function runs again, reset any state it sets in both branches, as shown above. Otherwise an old error can remain on screen after a later call succeeds.
Summary of rules
- A string starting with
$references a property or getter on the component. - The key must match the Apex parameter name.
- If any referenced value is
undefined, Apex is not called and no error is raised. - A change to a referenced value triggers a new evaluation. Replace objects instead of mutating them.
- Use a getter to compute a value or to turn "not ready" into
undefined. - Use a debounced field to limit calls from typed input.
Exercise
A component wires searchContacts with { accountId: '$recordId', term: '$term' }. The term field starts as an empty string, and users report that the component loads every contact for the account before they type anything. You want no Apex call until the user has typed at least three characters. What change do you make?
Show answer
Add a getter such as get minTerm() { return this.term && this.term.trim().length >= 3 ? this.term.trim() : undefined; } and change the wire to { accountId: '$recordId', term: '$minTerm' }. An empty string is a defined value, so the wire calls Apex with it. A getter that returns undefined for short input keeps the wire from calling Apex until the term is long enough.
Exercise
A wire references '$filters', where filters is an object. A handler runs this.filters.status = 'Closed', and the list does not update. Why, and how do you fix it?
Show answer
The handler changes the existing object in place, so the wire service may not detect a new value. Assign a new object instead, for example this.filters = { ...this.filters, status: 'Closed' };, and the wire re-runs.
Exercise
Your wire is @wire(getContacts, { accountId: '$recordID' }), but the class property is recordId. The component shows nothing and the console has no error. Explain what happens.
Show answer
'$recordID' refers to a property that does not exist, so its value is always undefined. The wire service does not call Apex when a referenced value is undefined, and it raises no error. Correct the spelling to '$recordId'.