Sub topic 7
Calling Apex imperatively for writes and on-demand reads
This chapter assumes you can write basic Apex classes with SOQL and DML. It also assumes you know the structure of a Lightning web component (LWC): a template, a JavaScript class, and decorators such as @api. You should also know that @AuraEnabled makes a static Apex method visible to components. The earlier chapters covered that annotation and @wire.
What "imperative" means
An imperative call is one that your JavaScript code starts itself, at the moment it chooses. You import the Apex method as a function and call it like any other function. It returns a promise. A promise is an object that represents a result that has not arrived yet. It later either resolves with the data or rejects with an error.
This differs from @wire. With @wire, the platform decides when to call the method, and it calls again when a reactive parameter changes. With an imperative call, nothing happens until your code runs the function.
Use an imperative call in these cases:
- The method changes data. Only methods without
cacheable=truecan run DML, and@wirecan only call cacheable methods. - The read should happen on demand, such as when the user clicks a button or presses Enter in a search box.
- You need to call several methods in a set order, where the second needs the first one's result.
- You want to decide in code when to call, for example only after validating input.
Imperative calls against a non-cacheable method
A method that writes data omits cacheable=true. Salesforce does not allow DML in a cacheable method, because the platform may serve a cached result without running the method again. A write that is silently skipped would be a serious bug.
Here is the Apex side.
public with sharing class ContactController {
@AuraEnabled
public static Contact createContact(String lastName, Id accountId) {
try {
Contact c = new Contact(LastName = lastName, AccountId = accountId);
insert as user c;
return c;
} catch (DmlException e) {
throw new AuraHandledException('Could not create the contact: ' + e.getMessage());
}
}
}Three details matter here.
- The method is
staticandpublic, as every@AuraEnabledmethod must be. insert as userruns the insert in user mode, so the running user's object and field permissions apply. If the user lacks create access, the insert throws instead of quietly succeeding.- The
catchblock converts aDmlExceptioninto anAuraHandledException. Chapter on error handling covers why. In short, the component receives a readable message instead of a generic one.
Now the component.
import { LightningElement, api } from 'lwc';
import createContact from '@salesforce/apex/ContactController.createContact';
export default class ContactCreator extends LightningElement {
@api recordId;
lastName = '';
error;
handleChange(event) {
this.lastName = event.target.value;
}
async handleSave() {
try {
const contact = await createContact({
lastName: this.lastName,
accountId: this.recordId
});
this.error = undefined;
console.log('Created contact', contact.Id);
} catch (error) {
this.error = error.body ? error.body.message : error.message;
}
}
}The import path has the form @salesforce/apex/ClassName.methodName. The imported name, createContact here, is a local function name, so you can choose any identifier.
Passing parameters
An imperative call takes one argument: an object whose property names match the Apex parameter names exactly. In the example, lastName and accountId must match String lastName, Id accountId. A misspelled key does not cause a compile error. The Apex parameter simply arrives as null, which often produces a confusing failure on the server.
If the method has no parameters, call it with no argument: await getAll();.
The two ways to consume the promise
You can use async and await, as above, or chain .then() and .catch(). Both are equivalent.
createContact({ lastName: this.lastName, accountId: this.recordId })
.then((contact) => {
this.error = undefined;
console.log('Created contact', contact.Id);
})
.catch((error) => {
this.error = error.body ? error.body.message : error.message;
});Pick one style and use it consistently in a component. The async form is easier to read when you have several sequential calls, because ordinary try/catch handles all of the errors in one place.
Imperative calls against a cacheable method
Cacheable methods can also be called imperatively. This is the usual choice for an on-demand read, such as a search triggered by a button.
public with sharing class ContactSearchController {
@AuraEnabled(cacheable=true)
public static List<Contact> search(String term) {
String pattern = '%' + String.escapeSingleQuotes(term) + '%';
return [
SELECT Id, Name, Email
FROM Contact
WHERE Name LIKE :pattern
WITH USER_MODE
ORDER BY Name
LIMIT 25
];
}
}import { LightningElement } from 'lwc';
import search from '@salesforce/apex/ContactSearchController.search';
export default class ContactSearch extends LightningElement {
term = '';
results = [];
error;
handleTermChange(event) {
this.term = event.target.value;
}
async handleSearch() {
try {
this.results = await search({ term: this.term });
this.error = undefined;
} catch (error) {
this.results = [];
this.error = error.body ? error.body.message : error.message;
}
}
}The query binds pattern with a colon, so it is a bind variable and not concatenated into the query string. That prevents SOQL injection. escapeSingleQuotes is not needed for a bind variable, and it is shown here only because it keeps a literal apostrophe out of the pattern. If you remove it, binding is still safe.
An imperative call to a cacheable method still benefits from the client cache. Calling it twice with the same parameters can return the stored result without a server round trip. This has a consequence covered below under stale data.
What the result looks like
The resolved value is the Apex return value serialized to JSON, then turned into a JavaScript value.
| Apex type returned | JavaScript value |
|---|---|
| `String`, `Integer`, `Boolean` | A primitive |
| `List<Contact>` | An array of plain objects |
| `Contact` (an sObject) | One plain object with the queried fields |
| Wrapper class with `@AuraEnabled` members | A plain object with only those members |
| `Map<String, Object>` | A plain object keyed by the map keys |
Fields you did not query are absent from the object. Reading contact.Phone when the query did not select Phone gives undefined, not an error.
Records returned by an imperative call are not read-only in the way wired results are. Wired data is frozen. Imperative results are plain objects you may modify. Even so, copy before editing if the same result also feeds a wire adapter or another component.
Control flow around the call
An imperative call gives you room to manage the user interface around it. A typical component tracks a busy flag so the user cannot submit twice.
import { LightningElement, api } from 'lwc';
import createContact from '@salesforce/apex/ContactController.createContact';
export default class ContactCreatorGuarded extends LightningElement {
@api recordId;
lastName = '';
error;
isSaving = false;
handleChange(event) {
this.lastName = event.target.value;
}
async handleSave() {
if (this.isSaving || !this.lastName) {
return;
}
this.isSaving = true;
try {
await createContact({
lastName: this.lastName,
accountId: this.recordId
});
this.error = undefined;
this.lastName = '';
} catch (error) {
this.error = error.body ? error.body.message : error.message;
} finally {
this.isSaving = false;
}
}
}The finally block runs whether the call succeeds or fails, so the flag always resets. Without it, one failed save would leave the button disabled for good.
The following diagram shows the lifecycle of one imperative call.
Reading the error object
When the promise rejects, the error is not a plain string. For an error thrown from Apex, it has this shape:
error.body.messageholds the message from the server. For anAuraHandledException, this is the text you passed to the constructor.error.statusholds the HTTP status code.error.statusTextholds the matching status text.
Errors raised on the client, such as a network failure or a JavaScript mistake inside your then handler, have no body. That is why the examples test error.body before reading error.body.message, and fall back to error.message.
When the Apex method throws an exception that is not an AuraHandledException, the message the client receives is usually a generic "Script-thrown exception". Wrap anticipated failures so users see something useful.
Edge cases and common errors
Stale data after a write
A cacheable read followed by a write can leave the screen showing old data. The write changed the server, but the cached read result is still stored on the client. If a wired list needs to update after your imperative save, call refreshApex on the wired property. A later chapter in this tutorial covers that. If the list itself came from an imperative cacheable call, call that method again. Because of the cache, you may get the stored result back. If you need guaranteed fresh data from a method you also write through, use a non-cacheable method for that read, and accept that every call goes to the server.
Calling a cacheable method for a write
If a method is marked cacheable=true and contains DML, the platform throws "DML operation not allowed" at run time. The fix is to remove cacheable=true and call that method imperatively.
Missing parameter names
An object key that does not match the Apex parameter name delivers null. Check spelling first when a method behaves as if the input were empty.
Sending the wrong types
Apex converts the JSON values you send. A string such as '001xx000003DGb2' converts to an Id if it is a valid ID. An invalid string causes a type conversion error. Dates are best sent as ISO strings like '2026-11-30'.
Race conditions between calls
If a user types quickly and each keystroke triggers search, responses can arrive out of order. The slowest older request may then overwrite the newest results. Guard against this by storing a request counter and ignoring any response that is not the latest one.
import { LightningElement } from 'lwc';
import search from '@salesforce/apex/ContactSearchController.search';
export default class LiveSearch extends LightningElement {
results = [];
latestRequest = 0;
async handleInput(event) {
const term = event.target.value;
const requestId = ++this.latestRequest;
try {
const data = await search({ term });
if (requestId === this.latestRequest) {
this.results = data;
}
} catch (error) {
if (requestId === this.latestRequest) {
this.results = [];
}
}
}
}In real components, also debounce the input. That means you wait until the user pauses typing before you call, so you send fewer requests.
Governor limits still apply
Each imperative call is a separate Apex transaction with its own governor limits. Calling a method in a loop from JavaScript is slow and wasteful. If you need to save ten records, send them together in one call as a list parameter and insert them in one DML statement.
@AuraEnabled
public static List<Contact> createContacts(List<Contact> contacts) {
try {
insert as user contacts;
return contacts;
} catch (DmlException e) {
throw new AuraHandledException('Could not create the contacts: ' + e.getMessage());
}
}Choosing between @wire and imperative
| Question | Choose |
|---|---|
| Does the method change data? | Imperative |
| Should the data load when the component appears and reload when a property changes? | `@wire` |
| Does a user action trigger the read? | Imperative |
| Do you need the result inside a handler before doing something else? | Imperative |
| Is the method cacheable and the call reactive? | `@wire` |
Both styles can call the same cacheable method. The method itself does not choose the style. Only the cacheable setting limits which styles are available.
Summary of the working model
- An imported Apex method is a function that returns a promise.
- You pass one object whose keys match the Apex parameter names.
- Success resolves with the serialized return value, and failure rejects with an error whose message is at
error.body.message. - Writes must be non-cacheable and must run through imperative calls.
- You manage loading state, double submits, and out-of-order responses yourself.
Exercise
A component calls a method imperatively and passes { acctId: this.recordId }. The Apex signature is getTotal(Id accountId). The method runs without an error but returns the wrong total, as if no account were given. What is the cause, and how do you fix it?
Show answer
The key acctId does not match the Apex parameter name accountId, so the parameter arrives as null. Rename the key to accountId: getTotal({ accountId: this.recordId }).
Exercise
You have a method saveNote that inserts a record and is marked @AuraEnabled(cacheable=true). Calling it from a component fails at run time. List the two changes needed, and explain why @wire is not an option for the corrected method.
Show answer
Remove cacheable=true from the annotation so the method may perform DML, and call it imperatively from the component. @wire is not an option because the wire service only supports cacheable methods, and a method that changes data must not be cacheable.
Exercise
Your save handler sets isSaving = true before the call and false inside the try block after the call. After one server error, the Save button stays disabled. Why, and what is the fix?
Show answer
When the call rejects, execution jumps to the catch block and skips the line that resets isSaving. Move the reset into a finally block, which runs on both success and failure.