Sub topic 3
Calling the method imperatively
An imperative call runs an Apex method at the moment your JavaScript decides to run it. This chapter covers what the imported function is, how to trigger it, and how an imperative call behaves differently from a wire call.
This chapter assumes you have read the previous two chapters. You should have an Apex method marked @AuraEnabled and a component that imports it with import searchContacts from '@salesforce/apex/ContactController.searchContacts'. You should also be comfortable with LWC event handlers and with Promises at a basic level. Parameters, Promise handling, loading state, and error display each get their own chapter. Here they appear only as far as the examples need them.
What "imperative" means
In a wire call, you declare what data you want, and the framework decides when to fetch it. It fetches when the component connects and again when a reactive parameter changes. In an imperative call, you write the call yourself. It runs when your code reaches that line, and not before.
The imported Apex method is an ordinary JavaScript function. You can call it like any other function, and it returns a Promise. The Promise resolves with the Apex return value, or rejects with an error object.
import { LightningElement } from 'lwc';
import getRecentContacts from '@salesforce/apex/ContactController.getRecentContacts';
export default class RecentContacts extends LightningElement {
contacts;
handleLoad() {
getRecentContacts()
.then((result) => {
this.contacts = result;
})
.catch((error) => {
console.error(error);
});
}
}Nothing is sent to the server until handleLoad runs. If the method takes no parameters, you call it with no arguments, as shown above.
The request lifecycle
The call is asynchronous. Your function returns immediately with a pending Promise. The browser sends the request, Apex runs on the server, and the result comes back later. Code after the call keeps running before the result arrives.
The diagram shows why you cannot write const data = searchContacts(...) and use data on the next line. The variable would hold a Promise and not the records. You must wait for the Promise with await or .then().
Triggering the call
You can start an imperative call from any JavaScript that runs in your component. Four triggers cover most cases.
| Trigger | Typical use | Notes |
|---|---|---|
| Event handler (click, change, submit) | Search button, save button | The most common case. The user decides when it runs. |
| `connectedCallback()` | Load data once when the component is inserted into the page | Works, but a wire adapter is often simpler for read-only data. |
| After another call completes | Chain a save, then a reload | Call the second function inside `.then()` or after an `await`. |
| `renderedCallback()` | Rare | Easy to create an infinite loop. Guard it with a flag. |
A handler that loads data on connect looks like this:
import { LightningElement } from 'lwc';
import getRecentContacts from '@salesforce/apex/ContactController.getRecentContacts';
export default class RecentContacts extends LightningElement {
contacts = [];
async connectedCallback() {
try {
this.contacts = await getRecentContacts();
} catch (error) {
this.contacts = [];
}
}
}connectedCallback can be declared async, because the framework ignores its return value. The component renders first with the empty contacts array, then rerenders when the assignment happens. Design the template so the empty state looks acceptable.
Using the result
The resolved value is the Apex return value serialized to JSON. An Apex List<Contact> becomes a JavaScript array of plain objects. Only the fields your SOQL query selected are present. Fields you did not query are undefined, not null.
Assign the result to a class field to display it. Class fields in LWC are reactive, so the assignment triggers a rerender. Mutating a nested property of an object that is already assigned also triggers a rerender, but only for properties that the template reads. Replacing the whole value is the clearest approach.
this.contacts = await getRecentContacts();The imperative result is a snapshot. Nothing updates it when the records change on the server. If another user edits a contact, your array does not change until you call the method again.
Imperative calls and cacheable methods
You can call a cacheable=true method imperatively, and the call still goes through the same function. Two behaviors are worth knowing:
- The client may serve a response from its cache for a repeated call with the same parameters. You can see a result that is slightly out of date, even though you called the method again.
- A cacheable method cannot perform DML. It cannot insert, update, or delete records, so a method that changes data must not be marked cacheable.
For methods that change data, omit cacheable=true. An imperative call is the only way to run such a method from LWC, because wire adapters require cacheable methods.
@AuraEnabled
public static void updateEmail(Id contactId, String email) {
// DML here, so the method is not cacheable
}Methods without cacheable=true always go to the server. That makes them the safe choice when you need fresh data on every call, such as a "Refresh" button, at the cost of an extra server round trip each time.
Common mistakes
These problems appear often when developers first call Apex imperatively.
- Forgetting to wait for the Promise. Code such as
this.contacts = getRecentContacts();stores a pending Promise in the field. The template then renders nothing useful, and no error is reported. - Calling the function in a getter. Getters run whenever the template rerenders. An imperative call inside one can fire many times, and the assignment inside the Promise can trigger yet another rerender. Put the call in a handler or lifecycle hook.
- Calling in
renderedCallbackwithout a guard. The call updates a field, the field change causes a render, andrenderedCallbackruns again. Use a boolean such ashasLoadedto run the call only once. - Assuming the order of overlapping responses. If a user clicks Search twice quickly, the second response can arrive before the first. The older response then overwrites the newer one. Track a request counter or disable the button while a call is pending, as the next chapters show.
- Importing a name that does not match. The path after
@salesforce/apex/must beClassName.methodName. A typo causes a deployment or build error, not a runtime error.
A complete small example
The Apex class below has one cacheable read method, with sharing and field-level security enforced. The component calls it from a button.
public with sharing class ContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> getRecentContacts() {
return [
SELECT Id, Name, Email
FROM Contact
WITH USER_MODE
ORDER BY CreatedDate DESC
LIMIT 10
];
}
}import { LightningElement } from 'lwc';
import getRecentContacts from '@salesforce/apex/ContactController.getRecentContacts';
export default class RecentContacts extends LightningElement {
contacts = [];
async handleLoad() {
try {
this.contacts = await getRecentContacts();
} catch (error) {
this.contacts = [];
}
}
}<template>
<lightning-card title="Recent Contacts">
<div class="slds-p-around_medium">
<lightning-button label="Load" onclick={handleLoad}></lightning-button>
<template for:each={contacts} for:item="contact">
<p key={contact.Id}>{contact.Name}</p>
</template>
</div>
</lightning-card>
</template>Before you click Load, the list is empty and no request has been sent. After the click, the handler runs, the Promise resolves, contacts changes, and the list renders. The catch block is deliberately minimal here. Showing the error to the user is covered in a later chapter.
Exercise
A developer writes connectedCallback() { this.contacts = getRecentContacts(); } with no await or .then(). What does this.contacts hold, and how should the line be fixed?
Show answer
It holds a pending Promise, not the list of contacts, so the template shows nothing useful and no error appears. Make the callback async and write this.contacts = await getRecentContacts(); inside a try/catch block. Alternatively, call .then((result) => { this.contacts = result; }) on the returned Promise.
Exercise
You need a "Save" button that updates a Contact's email through Apex. Should the Apex method be cacheable=true, and can you call it with a wire adapter?
Show answer
No to both. A method that performs DML must not be cacheable, and wire adapters accept only cacheable methods. Mark the method with plain @AuraEnabled and call the imported function imperatively from the button's click handler.