Calling Apex from LWC · Lesson 18 of 25
Call Apex Imperatively from LWC
Wired Apex runs automatically and is limited to read-only, cacheable methods. Whenever you need to decide when the call happens – on a button click, after validating a form, as the user types – or the method changes data, you call it imperatively: an imported Apex method is just an async function that returns a promise.
In this lesson
- Calling Apex on a button click, with loading and errors
- Saving data: DML from LWC
- A debounced search box
- @wire or imperative?
Saving data from a button
// CaseService.cls
public with sharing class CaseService {
@AuraEnabled
public static Id escalateCase(Id caseId, String reason) {
if (String.isBlank(reason)) {
throw new AuraHandledException('Please give a reason for escalating.');
}
Case c = new Case(Id = caseId, Status = 'Escalated', Priority = 'High', Description = reason);
update as user c; // DML in user mode: permissions enforced
return c.Id;
}
}
<!-- escalateCase.html -->
<template>
<lightning-card title="Escalate case">
<lightning-textarea label="Reason" value={reason} onchange={handleReason}></lightning-textarea>
<lightning-button label="Escalate" variant="destructive" onclick={escalate} disabled={isWorking}></lightning-button>
<template lwc:if={isWorking}>
<lightning-spinner alternative-text="Escalating" size="small"></lightning-spinner>
</template>
<p class="slds-text-color_error">{error}</p>
</lightning-card>
</template>
// escalateCase.js
import { LightningElement, api } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { notifyRecordUpdateAvailable } from 'lightning/uiRecordApi';
import escalateCase from '@salesforce/apex/CaseService.escalateCase';
export default class EscalateCase extends LightningElement {
@api recordId;
reason = '';
isWorking = false;
error = '';
handleReason(event) {
this.reason = event.detail.value;
}
async escalate() {
this.isWorking = true;
this.error = '';
try {
await escalateCase({ caseId: this.recordId, reason: this.reason }); // parameters by name
await notifyRecordUpdateAvailable([{ recordId: this.recordId }]); // LDS components reload the case
this.dispatchEvent(new ShowToastEvent({ title: 'Case escalated', variant: 'success' }));
} catch (e) {
this.error = e.body?.message ?? 'Something went wrong';
} finally {
this.isWorking = false;
}
}
}
▌Escalate case
Reason [] [Escalate]
› click “Escalate”
▌Escalate case
Reason [] [Escalate]
Please give a reason for escalating.
› type “Customer is a strategic account” into Reason
▌Escalate case
Reason [Customer is a strategic account] [Escalate]
Please give a reason for escalating.
› click “Escalate”
▌Escalate case
Reason [Customer is a strategic account] [Escalate]
toast (success): Case escalated
escalateCase called 2× with {"caseId":"500XX0000002Cs","reason":"Customer is a strategic account"}- Call the method with one object whose keys match the Apex parameter names.
- The method returns a promise:
awaitit insidetry/catch/finally, and drive a loading flag so the button can't be double-clicked. AuraHandledExceptionmessages arrive inerror.body.message– write them for users.- Apex DML isn't seen by Lightning Data Service, so
notifyRecordUpdateAvailabletells LDS to reload the record everywhere on the page.
A debounced search
Searching on every keystroke would call Apex dozens of times. Wait until the user pauses:
// AccountSearch.cls
public with sharing class AccountSearch {
@AuraEnabled(cacheable=true)
public static List<Account> search(String term) {
String pattern = '%' + term + '%';
return [SELECT Id, Name, Industry FROM Account WHERE Name LIKE :pattern WITH USER_MODE ORDER BY Name LIMIT 10];
}
}
<!-- accountSearchBox.html -->
<template>
<lightning-input type="search" label="Find an account" value={term} onchange={handleChange}></lightning-input>
<template for:each={results} for:item="acc">
<p key={acc.Id}>{acc.Name} · {acc.Industry}</p>
</template>
<p>{statusText}</p>
</template>
// accountSearchBox.js
import { LightningElement } from 'lwc';
import search from '@salesforce/apex/AccountSearch.search';
const DELAY = 300;
export default class AccountSearchBox extends LightningElement {
term = '';
results = [];
statusText = 'Type at least 2 letters';
timer;
handleChange(event) {
this.term = event.detail.value;
clearTimeout(this.timer); // restart the countdown on every keystroke
if (this.term.length < 2) {
this.results = [];
this.statusText = 'Type at least 2 letters';
return;
}
// eslint-disable-next-line @lwc/lwc/no-async-operation
this.timer = setTimeout(() => this.runSearch(this.term), DELAY);
}
async runSearch(term) {
try {
this.results = await search({ term });
this.statusText = `${this.results.length} found`;
} catch (e) {
this.statusText = e.body?.message ?? 'Search failed';
}
}
disconnectedCallback() {
clearTimeout(this.timer);
}
}
Find an account []
Type at least 2 letters
› type “a” into Find an account
Find an account [a]
Type at least 2 letters
› type “c” into Find an account
Find an account [ac]
Type at least 2 letters
› type “m” into Find an account
Find an account [acm]
Type at least 2 letters
› type “e” into Find an account
Find an account [acme]
Type at least 2 letters
› wait 400ms
Find an account [acme]
Acme Corporation · Manufacturing
Acme Logistics · Transportation
2 found
search called 1× with {"term":"acme"}Four keystrokes, one Apex call, made with the full term – the call list proves it. A cacheable method can be called imperatively too; it then benefits from the client cache.
@wire or imperative?
| Use @wire when… | Call imperatively when… |
|---|---|
| the component should load data as soon as it has its parameters | a user action triggers the call (click, submit, search) |
the method is read-only (cacheable=true) | the method changes data (DML) or calls out |
| you want automatic re-runs when parameters change | you need control: validation first, sequencing, Promise.all for parallel calls |
Security is on the server
Any @AuraEnabled method can be called by any user who has access to the Apex class – not only through your component. Check permissions in Apex (with sharing, USER_MODE, explicit checks for sensitive actions), and grant class access through permission sets only to users who need it.
Practice
Try it yourself
Call
QuoteService.applyDiscount({ quoteId, percent })from a button and show "New total: …" with the returned number.Show solution
<!-- discountButton.html --> <template> <lightning-button label="Apply 10% discount" onclick={apply}></lightning-button> <p>{message}</p> </template>// discountButton.js import { LightningElement, api } from 'lwc'; import applyDiscount from '@salesforce/apex/QuoteService.applyDiscount'; export default class DiscountButton extends LightningElement { @api recordId; message = ''; async apply() { try { const total = await applyDiscount({ quoteId: this.recordId, percent: 10 }); this.message = `New total: $${total.toLocaleString('en-US')}`; } catch (e) { this.message = e.body?.message; } } }[Apply 10% discount] › click “Apply 10% discount” [Apply 10% discount] New total: $13,500 applyDiscount called 1× with {"quoteId":"0Q0XX0000001Qt","percent":10}
Quick check
How do you pass parameters to an imperative Apex call?
As one object whose keys are the Apex parameter names.
Can a cacheable Apex method perform DML?
No – DML methods use plain @AuraEnabled and are called imperatively.
How do LDS components learn about a change made through Apex?
Call notifyRecordUpdateAvailable with the record Ids.
Summary
- Imperative Apex calls are async functions: await them in try/catch/finally with a loading flag.
- Use them for DML and user-triggered actions; debounce calls driven by typing.
- Throw AuraHandledException for user-facing errors, and enforce security in Apex.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.