Sub topic 7
Calling Apex imperatively for writes and on-demand reads
This chapter assumes you can write basic Apex (classes, SOQL, DML) and basic Lightning web components (templates, decorators, event handlers). It also assumes you know that @AuraEnabled exposes a static method to components. Here you will learn how to call that method from JavaScript at a moment you choose.
What "imperative" means
With @wire, the platform decides when to call Apex. It calls when the component renders and again when a reactive parameter changes. An imperative call works the other way. You import the Apex method as a function and call it yourself, usually inside an event handler. The call returns a promise, which is an object that later resolves with the result or rejects with an error.
Use an imperative call when:
- The method changes data. Methods that perform DML cannot be
cacheable=true, so they cannot be wired. - The read should happen only after a user action, such as a button click or a search.
- You need to control the timing, for example to call two methods in sequence.
The server side
A method used for writes must not be marked cacheable=true. Convert a DmlException into an AuraHandledException so the client receives a readable message.
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());
}
}
}insert as user runs the insert in user mode. It enforces the running user's object and field permissions, so a user without create access to Contact gets an error instead of a new record.
The client side
Import the method with the @salesforce/apex scope. The import name becomes a function that takes one object. Its keys must match the Apex parameter names exactly.
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 flow of one call looks like this:
How the call behaves
- Parameter names matter. If the Apex parameter is
accountId, the JavaScript key must beaccountId. A mismatch sendsnullfor that parameter. - The promise rejects on server errors. The rejection value is an object. The message from
AuraHandledExceptionis inerror.body.message. Network or client failures may have nobody, which is why the example falls back toerror.message. - Nothing refreshes automatically. After a write, any wired data that shows the same records is still the cached copy. Refresh it with
refreshApex, covered in a later chapter. - Imperative calls to cacheable methods work too. You can call a
cacheable=truemethod imperatively for an on-demand read. The client may still serve a cached result.
Common errors
| Symptom | Likely cause |
|---|---|
| `TypeError: createContact is not a function` | Wrong import path, or the Apex method is not `static` and `@AuraEnabled`. |
| A parameter arrives as `null` in Apex | The JavaScript key does not match the Apex parameter name. |
| `error.body` is undefined | The failure happened on the client or network, so there is no server body. |
| Error says DML is not allowed | The method is marked `cacheable=true`. Remove the flag for writes. |
| Generic "Script-thrown exception" message | The method threw a plain exception instead of `AuraHandledException`. |
Exercises
Exercise
A button handler must insert a Contact. Why can you not use @wire for this, and what do you use instead?
Show answer
Methods that perform DML cannot be marked cacheable=true, and @wire requires a cacheable method. Import the non-cacheable method and call it imperatively in the handler, awaiting the promise.
Exercise
An imperative call to getTotal({ acctId: this.recordId }) always reaches Apex with a null value, though the Apex signature is getTotal(Id accountId). What is wrong and how do you fix it?
Show answer
The JavaScript key acctId does not match the Apex parameter name accountId. Change the call to getTotal({ accountId: this.recordId }).