Sub topic 10
When to Call Apex Imperatively Instead
This chapter assumes you can write an @AuraEnabled(cacheable=true) method, import it into a component, and wire it to a property or function. It also assumes you know basic async/await and try/catch in JavaScript.
What "imperative" means
A wired call is declarative. You describe what data you want, and the platform decides when to fetch it. An imperative call is one you make yourself, at a moment you choose. The imported Apex method is a function that returns a promise, so you call it like any other async function.
The same import works for both styles:
import getContacts from '@salesforce/apex/ContactController.getContacts';When imperative is the better choice
Use an imperative call when the wire's automatic behavior gets in the way:
- A user action starts the load. A button click, a search submit, or a "Load more" link should trigger the call. A wire runs as soon as its parameters are defined.
- The Apex method changes data. Methods that insert, update, or delete cannot be
cacheable=true, and wires require cacheable methods. These can only be called imperatively. - You need to control timing. You may need to run calls in sequence, or run one after another call finishes.
- You want the result as a return value. You can use it right away in the same function, rather than waiting for a wire to provision a field.
A worked example
This component loads contacts only when the user clicks a button. It reuses the Apex method from earlier chapters.
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;
}
}
}Three details matter here:
- You pass parameters as a plain object. There is no
$prefix, because nothing is reactive. You readthis.recordIdat the moment of the call. - Errors arrive as a rejected promise, so you handle them with
catch. You do not get an{ data, error }object. - You clear the opposite field after each outcome. Otherwise an old error can stay on screen next to fresh data.
The template can use the same pattern as the wired version:
<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>Behavior differences from a wire
| Aspect | `@wire` | Imperative |
|---|---|---|
| Starts | Automatically | When you call it |
| Reacts to parameter changes | Yes, with `$` | No, you call again |
| Result | `{ data, error }` | Resolved value or rejected promise |
| Method must be cacheable | Yes | No |
| Refresh | `refreshApex` | Call the method again |
Common mistakes
- Calling the method in
connectedCallbackand also wiring it. This runs the request twice. - Forgetting
await. Without it,this.rowsholds a pending promise, and the template shows nothing. - Reading
error.messageonly. Apex errors put the useful text inerror.body.message, so checkerror.bodyfirst. - Not handling the rejected promise. An uncaught rejection leaves the user with no feedback.
Exercise
A "Save" button must insert a Contact with Apex, then show the new contact in a list. Can you use @wire for the insert? Which style fits, and why?
Show answer
No. Wires only work with cacheable methods, and a method that inserts a record cannot be cacheable=true. Call the insert method imperatively from the click handler and handle failure with catch. To update the list afterward, call the read method again, or call refreshApex if the list is wired.
Exercise
Your imperative handler sets this.rows from the result, but the list never appears and the console shows no error. What is the most likely cause, and what is the fix?
Show answer
The await keyword is missing, so this.rows is assigned a pending promise instead of the contact array. Add await before the call, and make the handler async.