Sub topic 10
When to call Apex imperatively instead
This chapter assumes you can write a cacheable @AuraEnabled method, import it into a component, and wire it to a property or function. Here you will learn when a wire is the wrong tool and how to call the same Apex method imperatively.
What "imperative" means
An imperative call is one your code makes on purpose, at a moment you choose. When you import an Apex method, the import is a function. You can pass it to @wire, or you can call it directly. Called directly, it returns a promise. The promise resolves with the method's return value or rejects with an error.
import getContacts from '@salesforce/apex/ContactController.getContacts';
getContacts({ accountId: '001000000000001AAA' })
.then((result) => console.log(result))
.catch((error) => console.error(error));A wire is declarative. You describe what data you want, and the framework decides when to fetch it. An imperative call reverses that. You decide when, and you handle the result yourself.
When to prefer an imperative call
Use an imperative call when any of the following is true.
- The call is triggered by a user action. A button click, a search submit, or a "Load more" link. A wire runs when the component renders or when a reactive parameter changes, not when the user asks.
- The Apex method is not cacheable. Wires require
@AuraEnabled(cacheable=true). A method that inserts, updates, or deletes data cannot be cacheable, so it can only be called imperatively. - You need to control timing. For example, you must wait for another call to finish first, or you want to debounce typing.
- You need to chain calls. The second call depends on the result of the first.
- You want a fresh result every time. A wire can return cached data. An imperative call to a cacheable method can also return cached data, but you can change that. See the caching section below.
- You do not want automatic re-runs. Reactive parameters re-run a wire whenever they change. If that would send too many requests, an imperative call avoids it.
If none of these apply, a wire is usually simpler. It needs less code, and it manages loading and updates for you.
The decision at a glance
A worked example
Suppose a component shows contacts only after the user clicks a button. The Apex method is the same one used in 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 component imports the method and calls it inside a click handler.
import { LightningElement, api } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactImperative extends LightningElement {
@api recordId;
rows;
errorMessage;
async handleLoad() {
try {
this.rows = await getContacts({ accountId: this.recordId });
this.errorMessage = undefined;
} catch (error) {
this.rows = undefined;
this.errorMessage = error.body ? error.body.message : error.message;
}
}
}The template adds a button and renders the result.
<template>
<lightning-button label="Load contacts" onclick={handleLoad}></lightning-button>
<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>Compare this with the wired version. Four things changed.
- You pass parameters as a plain object. There is no
$prefix, because nothing is reactive. You readthis.recordIdat the moment of the call. - The result is the value itself. A wire gives you
{ data, error }. An imperative call resolves with the data directly, so you useawaitor.then. - You handle errors yourself. A rejected promise throws. You catch it with
try/catchor.catch. - You reset state yourself. Clearing
rowswhen an error happens, and clearingerrorMessageon success, is your job. A wire'sdataanderrorare updated for you.
Handling errors in imperative calls
The rejected value has the same shape as a wire's error. For Apex errors, error.body.message holds the message. Network or client-side failures may not have a body, which is why the example falls back to error.message.
An imperative call does not set any loading flag. If you want a spinner, add one yourself and clear it in a finally block so it also clears on failure.
import { LightningElement, api } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactWithSpinner extends LightningElement {
@api recordId;
rows;
errorMessage;
isLoading = false;
async handleLoad() {
this.isLoading = true;
try {
this.rows = await getContacts({ accountId: this.recordId });
this.errorMessage = undefined;
} catch (error) {
this.rows = undefined;
this.errorMessage = error.body ? error.body.message : error.message;
} finally {
this.isLoading = false;
}
}
}Calling methods that change data
Methods that write to the database cannot be wired. They omit cacheable=true.
public with sharing class ContactWriter {
@AuraEnabled
public static Contact renameContact(Id contactId, String lastName) {
Contact c = [
SELECT Id, LastName
FROM Contact
WHERE Id = :contactId
WITH USER_MODE
LIMIT 1
];
c.LastName = lastName;
update as user c;
return c;
}
}The component calls it from a handler.
import { LightningElement } from 'lwc';
import renameContact from '@salesforce/apex/ContactWriter.renameContact';
export default class ContactRename extends LightningElement {
contactId = '003000000000001AAA';
message;
async handleRename() {
try {
const updated = await renameContact({
contactId: this.contactId,
lastName: 'Rivera'
});
this.message = 'Saved ' + updated.LastName;
} catch (error) {
this.message = error.body ? error.body.message : error.message;
}
}
}The update as user statement enforces the running user's permissions on the write, matching WITH USER_MODE on the query.
Writes also cause stale wires. If another part of the component displays a wired list of contacts, it does not know the record changed. After the write succeeds, call refreshApex on the wired result, as covered in the previous chapter.
Caching and imperative calls
Cacheable methods can be called imperatively, and the client may serve a cached response. Two points matter.
- A method without
cacheable=trueis never served from the client cache. Every call reaches the server. - A method with
cacheable=truecan return a stored value on repeated calls with the same parameters. If you need the latest data after a change, either refresh a wire withrefreshApex, or move the call to a method that is not cacheable.
Do not remove cacheable=true just to avoid a cache problem if the method is also wired somewhere. A wired method must stay cacheable.
Combining a wire and an imperative call
The two approaches work together. A common pattern is to wire the initial load, then call imperatively for later actions.
import { LightningElement, api, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import getContacts from '@salesforce/apex/ContactController.getContacts';
import renameContact from '@salesforce/apex/ContactWriter.renameContact';
export default class ContactManager extends LightningElement {
@api recordId;
wiredResult;
rows;
message;
@wire(getContacts, { accountId: '$recordId' })
wiredContacts(result) {
this.wiredResult = result;
if (result.data) {
this.rows = result.data;
}
}
async handleRename(event) {
const contactId = event.target.dataset.id;
try {
await renameContact({ contactId, lastName: 'Rivera' });
await refreshApex(this.wiredResult);
this.message = 'Updated';
} catch (error) {
this.message = error.body ? error.body.message : error.message;
}
}
}The wire loads the list when the component renders. The imperative call changes a record. refreshApex then brings the list up to date.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Using `$` in an imperative parameter, such as `{ accountId: '$recordId' }` | The literal string `$recordId` is sent to Apex and the call fails or returns nothing | Pass `this.recordId` |
| Calling the method in `connectedCallback` and expecting it to react to changes | The call runs once, so later changes to `recordId` are ignored | Use a wire, or call again when the value changes |
| Forgetting to `await` or return the promise | The handler finishes before the data arrives, and errors go unhandled | Use `await`, or return the promise |
| Reading `result.data` from an imperative call | The value is `undefined` because the result is the data itself | Use the resolved value directly |
| Calling a non-cacheable method with `@wire` | Deployment or runtime error | Add `cacheable=true` if the method has no DML, or call it imperatively |
| Expecting a second imperative call to bypass the cache | A cacheable method may return a stored value | Use a non-cacheable method when freshness matters |
Summary of the trade-offs
| Concern | `@wire` | Imperative call |
|---|---|---|
| Trigger | Render or reactive change | Your code decides |
| Method requirement | Must be cacheable | Cacheable or not |
| Result shape | `{ data, error }` | Resolved value or rejection |
| Parameters | Reactive with `$` | Plain values at call time |
| Loading and errors | Provisioned for you | Handled by you |
| Writes (DML) | Not possible | Supported |
Exercise
A component must save a changed phone number when the user clicks Save. A wired list on the same page shows the contact's phone number. Which approach do you use for the save, why can it not be wired, and what do you do afterward so the list is correct?
Show answer
Call the Apex method imperatively from the click handler. A save performs DML, so the method cannot be cacheable, and wires require cacheable=true. After the promise resolves, call refreshApex with the whole value the wire provisioned, so the wired list requests fresh data from the server.
Exercise
A developer writes const data = await getContacts({ accountId: '$recordId' }); inside a click handler. Describe what goes wrong and give the corrected line.
Show answer
The $ prefix only works in a wire configuration. In an imperative call, the string '$recordId' is sent to Apex literally, so the query does not match the intended account. The corrected line is const data = await getContacts({ accountId: this.recordId });.