Sub topic 6
Wiring to a Function for Custom Handling
This chapter assumes you can write a basic LWC with @api properties, that you know ES module imports and destructuring, and that you have already wired an Apex method to a property. The Apex method is the ContactController.getContacts method from earlier chapters.
Why wire to a function
When you wire to a property, the platform puts an object with data and error on that property. The template reads contacts.data directly. This works well when you only display the result.
Sometimes you need to act on the result. You may want to copy the records into your own fields, reshape them, or pull a message out of the error. In those cases, wire to a function instead. The platform calls your function each time the wire provisions a value.
The pattern
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 function receives one argument, an object with data and error. Destructuring in the parameter list pulls out the two values you need.
Three details matter here:
- Only one of
dataanderroris set on a given call. The other isundefined. - The function name is not special. The
@wiredecorator above it is what connects it to the adapter. - The
$recordIdparameter is reactive. WhenrecordIdchanges, the wire re-runs and your function is called again.
How the call flows
Resetting the other field
Notice that each branch clears the field it does not use. Without that, a failed call after a successful one leaves old rows next to a new error message. Always set both fields in each branch.
Rendering the result
The template reads your own fields, not the wire result:
<template>
<template lwc:if={rows}>
<ul>
<template for:each={rows} for:item="contact">
<li key={contact.Id}>{contact.Name}</li>
</template>
</ul>
</template>
<template lwc:elseif={errorMessage}>
<p>{errorMessage}</p>
</template>
</template>Property or function: which one
| Need | Use |
|---|---|
| Show data and error as they arrive | Wire to a property |
| Copy or transform data before display | Wire to a function |
| Extract an error message once, in JavaScript | Wire to a function |
| Keep the whole result for `refreshApex` | Wire to a function that stores the result |
The last row is covered in a later chapter. A function wire can store the entire argument so you can pass it to refreshApex later.
Common errors
- Expecting a return value. The platform ignores whatever your function returns. Assign to fields instead.
- Mutating
data. The object the wire provisions is read-only. If you need to sort or add fields, copy it first, for example withdata.map(c => ({ ...c, label: c.Name })). - Forgetting that the function may run before data exists. With a reactive parameter set to
undefined, the wire does not call Apex. If you handle both branches, nothing breaks when the value is not ready. - Reading
error.body.messagewithout a guard. Not every error has abody. A JavaScript error has onlymessage. The ternary in the example covers both.
Exercise
Exercise
A component wires getContacts to a function. The first call succeeds and rows holds 10 contacts. The user then changes recordId to a record they cannot access, and the call fails. The handler sets only this.errorMessage in the error branch. What does the user see, and how do you fix it?
Show answer
The template still shows the 10 old contacts, because rows was never cleared, and the error message may appear alongside them. Fix it by setting this.rows = undefined in the error branch, and by setting this.errorMessage = undefined in the data branch.