Sub topic 6
Wiring to a function for custom handling
Wiring to a property gives you an object with data and error, and the template reads it directly. That is enough when you display the server result unchanged. Wiring to a function lets you run your own code each time the wire provisions a value. You can reshape the rows, set several fields at once, extract an error message, or trigger a side effect.
This chapter assumes you can write a cacheable @AuraEnabled method, import it from @salesforce/apex/..., and wire it to a property with a reactive $recordId parameter. It also assumes you are comfortable with destructuring in JavaScript.
What changes when you wire to a function
You place @wire on a method instead of a field. The wire service calls that method and passes one argument, an object with data and error properties. Exactly one of them is normally set.
import { LightningElement, api, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactListFn extends LightningElement {
@api recordId;
rows;
errorMessage;
@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 configuration is the same as for a property: the imported method and a parameters object. Only the target changed. The method name wiredContacts is arbitrary. The component stores results in its own fields, rows and errorMessage, so the template no longer needs to know about the wire's result object.
Property or function
| Aspect | Wire to a property | Wire to a function |
|---|---|---|
| What you get | A field holding `{ data, error }` | A call with `{ data, error }` as the argument |
| Template access | `contacts.data`, `contacts.error` | Whatever fields you set |
| Transforming data | Needs a getter that reads `contacts.data` | Done once, inside the function |
| Side effects | Not possible at the wire | Possible inside the function |
| Amount of code | Least | More, and you must clear stale state yourself |
Choose a property when the template can use the result as it arrives. Choose a function when the component needs to do something with the result.
When the function runs
The wire service calls your function whenever it has a new value to provision. That happens in these cases:
- The component is connected and the parameters are defined, so the first result or error arrives.
- A reactive parameter changes and the call runs again with the new value.
- A refresh through
refreshApexreturns new data.
The function does not run on a timer or when the component re-renders. If a reactive parameter is undefined, such as $recordId before the platform sets it, the wire does not call the server for that configuration. Do not rely on the function seeing a fixed number of invocations. Write it so each call is safe on its own.
flowchart TDThe diagram below shows the decision inside a typical handler.
Clear the other side every time
Each call replaces the previous state. If the first call succeeded and a later call (after a parameter change) fails, the old rows would still be on screen next to the new error unless you clear them. That is why both branches in the example reset the other field. Forgetting this is the most common bug in function-wired components, and it appears only after the second call, so a quick manual test often misses it.
The reverse also matters. Setting this.errorMessage = undefined in the success branch removes a banner that was shown after an earlier failure.
Transforming data before display
A common reason to use a function is to build display values. The next example adds a label and a flag to each contact, and exposes a getter for the template.
import { LightningElement, api, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactCards extends LightningElement {
@api recordId;
rows = [];
errorMessage;
@wire(getContacts, { accountId: '$recordId' })
wiredContacts({ data, error }) {
if (data) {
this.rows = data.map((contact) => ({
...contact,
label: contact.Email
? `${contact.Name} (${contact.Email})`
: contact.Name,
hasEmail: Boolean(contact.Email)
}));
this.errorMessage = undefined;
} else if (error) {
this.rows = [];
this.errorMessage = error.body ? error.body.message : error.message;
}
}
get hasRows() {
return this.rows.length > 0;
}
}<template>
<template lwc:if={errorMessage}>
<p class="slds-text-color_error">{errorMessage}</p>
</template>
<template lwc:elseif={hasRows}>
<ul>
<template for:each={rows} for:item="contact">
<li key={contact.Id}>{contact.label}</li>
</template>
</ul>
</template>
<template lwc:else>
<p>No contacts found.</p>
</template>
</template>The spread ...contact creates a new object. This matters because the data the wire provides is read-only. Assigning data[0].label = 'x' fails or is silently ignored, depending on the context. Always copy before you add or change properties.
The template shows "No contacts found." both while the first call is in flight and after an empty result, because rows starts as an empty array. If the difference matters, add a loaded field. Set it to true in both branches of the function, and use it in the template.
Reading the error
Errors from Apex arrive as an object whose body.message holds the message. Errors that never reached Apex, such as a network failure, may have no body, so the example falls back to error.message. Keep that guard. Without it, a TypeError inside your handler hides the original problem.
Be careful about what the message may reveal. Apex exception messages are shown to the user as written. If the message could include internal details, throw an AuraHandledException in Apex with a user-safe message, and keep the details in a debug log.
A shared helper keeps this logic in one place:
export function reduceError(error) {
if (!error) {
return undefined;
}
if (Array.isArray(error.body)) {
return error.body.map((e) => e.message).join(', ');
}
if (error.body && typeof error.body.message === 'string') {
return error.body.message;
}
return error.message || 'Unknown error';
}Some errors, for example from Lightning Data Service adapters, carry an array in body. The helper handles both shapes, so the handler becomes this.errorMessage = reduceError(error);.
Keeping the wired result for refreshApex
A function that copies data into your own field has a side effect. You no longer hold the object the wire provisioned, and refreshApex needs that object. The next section's tool, refreshApex, takes the whole value the wire delivered, not your copy. The fix is to store the entire argument:
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);
}
}Here the parameter is named result instead of being destructured, so the component can keep it. When refreshApex completes, the wire service calls wiredContacts again with the fresh result, and the handler updates rows. The chapter on refreshApex covers the details of when and why to call it.
Gotchas
- Do not call the wired function yourself. The wire service owns it. If you need to load data on a button click, use an imperative call.
- Do not make the function
async. The wire service does not wait for a promise, so any error thrown after anawaitwould go unhandled. Do the work synchronously. If the result needs more asynchronous work, start it from the handler and manage its state in separate fields. - Avoid changing a reactive parameter inside the handler. If the handler updates a field that the wire config reads through
$, it can trigger another call, which calls the handler again. Such a loop is easy to create by accident. - Do not assume
this.recordIdis current inside the function. The result belongs to the parameters used for that request. When parameters change quickly, treat each call independently. - Empty is not an error. An Apex method that finds no rows returns an empty list, which arrives in
data. Handle that in the template, not in theerrorbranch.
Summary of the pattern
- Put
@wire(apexMethod, { param: '$field' })on a method. - Accept
{ data, error }, or the wholeresultif you plan to refresh. - In each branch, set your own fields and clear the opposite ones.
- Copy
databefore changing it. - Convert
errorto a short message with a guarded read oferror.body.message.
Exercise
A component wired to a function shows a list. The user changes a filter, which changes a reactive parameter, and the new request fails. The red error message appears, but the old list is still visible below it. What is missing, and where should the fix go?
Show answer
The error branch does not clear the stored rows. Add this.rows = undefined; (or an empty array) in the else if (error) branch of the wired function. Each call replaces the previous state, so each branch must reset the field belonging to the other outcome. Likewise the success branch should set errorMessage to undefined.
Exercise
Your handler does this.rows = data; and then in a click handler runs this.rows[0].selected = true;. The flag does not stick, or the code throws. Why, and how do you change the handler so you can mark rows as selected?
Show answer
The data the wire provisions is read-only, and this.rows points at that same object. Copy it when storing, for example this.rows = data.map((row) => ({ ...row, selected: false }));. The copies are plain objects the component owns, so changing selected on them works.
Exercise
You need to call refreshApex after a user saves a record, but your wired function destructures ({ data, error }) and copies data into rows. What must you change so that refreshApex can work?
Show answer
Keep the whole value the wire provisioned. Change the signature to accept result, store it in a field such as this.wiredResult = result, read result.data and result.error for your own state, and call refreshApex(this.wiredResult) from the save handler.