Sub topic 10
Wire service or imperative call: choosing
You can call the same Apex method from a Lightning web component in two ways. The wire service calls it for you and re-calls it when inputs change. An imperative call runs when your code calls it. This chapter gives you a way to decide between them and shows where mixing them is the right answer.
This chapter assumes you know the @AuraEnabled and cacheable=true basics from earlier chapters, can write an async function in JavaScript, and have a component that already imports an Apex method.
The two models
With the wire service, you declare what data the component needs. The platform decides when to fetch it. The method runs when the component is connected and all its parameters are defined. It runs again whenever a reactive parameter changes.
With an imperative call, you decide when to fetch. Nothing happens until your code invokes the imported function, and it returns a Promise.
Here is the contact search from earlier chapters, rewritten with the wire service.
import { LightningElement, wire } from 'lwc';
import searchContacts from '@salesforce/apex/ContactController.searchContacts';
export default class ContactSearchWire extends LightningElement {
searchTerm = '';
@wire(searchContacts, { searchTerm: '$searchTerm' })
contacts;
handleTermChange(event) {
this.searchTerm = event.target.value;
}
}<template>
<lightning-input label="Name" value={searchTerm} onchange={handleTermChange}></lightning-input>
<template lwc:if={contacts.error}>
<p class="slds-text-color_error">{contacts.error.body.message}</p>
</template>
<template lwc:if={contacts.data}>
<template for:each={contacts.data} for:item="contact">
<p key={contact.Id}>{contact.Name} ({contact.Email})</p>
</template>
</template>
</template>The $ prefix in '$searchTerm' marks the parameter as reactive. Each time searchTerm changes, the wire service re-provisions the data. There is no loading flag, no try/catch, and no click handler. The property contacts holds an object with data and error.
What differs in practice
| Concern | Wire service | Imperative call |
|---|---|---|
| Apex requirement | Method must be `cacheable=true` | Works with cacheable and non-cacheable methods |
| Trigger | Component connects, or a reactive parameter changes | Your code calls the function |
| DML (insert, update, delete) | Not allowed, because the method must be read-only | Allowed when the method is not cacheable |
| Result shape | `{ data, error }` object or a handler function that receives it | Resolved value or a rejected error |
| Loading state | You infer it: neither `data` nor `error` is set yet | You set it yourself |
| Returned data | Read-only (frozen) objects | Plain objects you can change |
| Refresh | `refreshApex` on the wired result | Call the function again |
| Parameters | Wire skips the call if a reactive parameter is `undefined` | Whatever you pass is sent |
Two rows in this table cause the most trouble.
The first is read-only data. Wire results are frozen. If you sort this.contacts.data in place or set a property on one of its records, you get an error or a silent failure. Copy first with [...data] or data.map(r => ({ ...r })). Data returned from an imperative call does not have this limit.
The second is the undefined rule. If a reactive parameter is undefined, the wire service does not call Apex at all. Initializing searchTerm to undefined is a common way to say "wait until the user picks something". An empty string '' is a real value, so the call goes ahead. A null parameter is also sent to Apex.
A decision procedure
Work through these questions in order. The first one that applies decides.
- Does the method change data (DML) or call out to an external system? Use an imperative call. It cannot be
cacheable=true, so it cannot be wired. - Should the call run only after a user action, such as a button click or a form submit? Use an imperative call.
- Do you need to call the method several times in sequence, or choose the method or its arguments in code? Use an imperative call. A wire adapter is fixed at declaration time.
- Is the data a read-only view of the server that should follow some reactive property or load when the component appears? Use the wire service.
- Both would work? Prefer the wire service. It has less code and less state to get wrong, and it is the model Lightning Data Service uses.
Cases where the answer is not obvious
Searching as the user types
A wire bound to a text input fires on every change. That means a request for each keystroke, and the responses are not guaranteed to be processed in the order you would want. If you want the wire, add a short delay between the input and the reactive property:
handleTermChange(event) {
const value = event.target.value;
window.clearTimeout(this.delayTimeout);
this.delayTimeout = window.setTimeout(() => {
this.searchTerm = value;
}, 300);
}If a search should happen only when the user asks for it, the imperative button-click version from the earlier chapters is simpler and has no timer to manage.
Cacheable methods called imperatively
A cacheable=true method can be called imperatively. That is useful when you want the caching behavior but also need on-demand timing. The cost is that you may get a cached result. If the record changed on the server and you need the latest values, a repeated imperative call to a cacheable method is not a guarantee of fresh data. Either make the read method non-cacheable, which costs you the client cache and the wire option, or arrange a refresh after the change (see the next section).
Loading on connect, but not as a wire
Sometimes a component needs one initial load that depends on logic, such as a value read from a custom permission or computed from several properties. You can call the method imperatively from connectedCallback. Remember that public properties set by a parent are not guaranteed to be set at that point in every case, so prefer a wire if the load depends on an @api property that may change later.
Mixing both in one component
Reads and writes often belong in one component. Wire the read so that it tracks its inputs. Call the write imperatively, then refresh the wired result. The @wire decorator can be applied to a function, which gives you the whole result object to keep for refreshApex.
import { LightningElement, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import searchContacts from '@salesforce/apex/ContactController.searchContacts';
import updateEmail from '@salesforce/apex/ContactController.updateEmail';
export default class ContactList extends LightningElement {
searchTerm = 'a';
contacts = [];
errorMessage;
wiredResult;
@wire(searchContacts, { searchTerm: '$searchTerm' })
handleWire(result) {
this.wiredResult = result;
const { data, error } = result;
if (data) {
this.contacts = data;
this.errorMessage = undefined;
} else if (error) {
this.contacts = [];
this.errorMessage = error?.body?.message || 'Unknown error';
}
}
async handleEmailBlur(event) {
const contactId = event.target.dataset.id;
const email = event.target.value;
try {
await updateEmail({ contactId, email });
await refreshApex(this.wiredResult);
} catch (error) {
this.errorMessage = error?.body?.message || 'Unknown error';
}
}
}The template would render each contact with a lightning-input that has data-id={contact.Id}, value={contact.Email}, and onblur={handleEmailBlur}. The save is imperative because it changes data. The list is wired because it is a read that follows searchTerm. The next chapter on refreshing data covers refreshApex in more detail.
Do not mutate this.contacts when it points at wire data. If you need a changed copy, build a new array.
Common errors
- Wiring a non-cacheable method. The deployment or the component fails to load, because the wire service needs
cacheable=true. Either add the option, if the method is truly read-only, or call it imperatively. - Putting DML in a cacheable method. The platform rejects DML in a method marked
cacheable=true. Split the read and the write into two methods, assearchContactsandupdateEmailare in the controller from the first chapter. - Expecting the wire to run when a parameter is
undefined. The method is never called, and no error appears. Check the parameter's initial value. - Forgetting the
$prefix. Without it, the wire service sends the literal string'searchTerm'as the argument and never reacts to changes. - Treating wire data as editable. Copy it before sorting or changing it.
- Reading the result before it arrives. In a wired property,
dataanderrorare bothundefineduntil the first response. Guard template expressions withlwc:if.
Summary of the choice
Choose by who controls timing and whether the method changes data. If the platform should control timing for a read-only query, wire it. If your code or the user controls timing, or the method writes data, call it imperatively. Many real components do both.
Exercise
A component must show a list of open cases for the account passed in through an @api property accountId, and must also have a "Close case" button that runs an Apex method that updates the case status. Which approach would you use for each part, and how does the list stay correct after a case is closed?
Show answer
Wire the read method (cacheable=true) with the reactive parameter { accountId: '$accountId' }, so the list loads when the component appears and reloads if the parent changes accountId. Call the close method imperatively, because it performs DML and cannot be cacheable, and it runs only on a button click. Keep the whole wired result (use the function form of @wire, or a wired property) and call refreshApex on it after the imperative call resolves, so the list shows the new status.
Exercise
A wired search returns no results and no error, and the Apex method is never called. The component sets searchTerm to undefined in its field declaration and uses { searchTerm: '$searchTerm' }. Why, and how would you change it so the search runs on load with all contacts?
Show answer
A wire adapter skips the call when any reactive parameter is undefined. Initialize searchTerm to an empty string '' (and have the Apex method treat an empty string as "match all", for example by building the LIKE key as '%' + searchTerm + '%'). The wire then runs once on connect and again each time searchTerm changes.