Sub topic 3
Calling the method imperatively
This chapter assumes you can write a basic LWC (template, decorators, event handlers), understand JavaScript Promises, and have an @AuraEnabled Apex method already imported into your component. Here you will make the call itself.
What "imperative" means
An imperative call runs when your code decides to run it. You call the imported function from an event handler, a lifecycle hook, or any other JavaScript. The wire service works differently. It calls Apex for you and re-runs the call when its reactive inputs change.
The imported Apex method is a plain function. Calling it returns a Promise. That Promise resolves with the Apex return value or rejects with an error object.
The call, step by step
The example controller from the previous chapters exposes searchContacts. It is imported like this:
import searchContacts from '@salesforce/apex/ContactController.searchContacts';A button click handler can then call it:
import { LightningElement } from 'lwc';
import searchContacts from '@salesforce/apex/ContactController.searchContacts';
export default class ContactSearch extends LightningElement {
searchTerm = '';
contacts = [];
handleTermChange(event) {
this.searchTerm = event.target.value;
}
async handleSearch() {
this.contacts = await searchContacts({ searchTerm: this.searchTerm });
}
}The template wires the button to the handler:
<template>
<lightning-input label="Name" value={searchTerm} onchange={handleTermChange}></lightning-input>
<lightning-button label="Search" onclick={handleSearch}></lightning-button>
</template>Three things happen in handleSearch:
- The function sends the request to the server with the parameters you give it.
awaitpauses the handler until the Promise settles. The browser stays responsive.- On success, the returned
List<Contact>becomes a JavaScript array and is assigned tocontacts. Becausecontactsis a class field, the template re-renders.
Sequence of events
Where you can call it
Imperative calls are not limited to clicks. Common places include:
- Event handlers, such as
onclick,onchange, and custom events. connectedCallback, when you need data as soon as the component loads and the method is not a good fit for@wire.- A
thencallback of another Promise, when one call depends on the result of another.
Do not call Apex from renderedCallback without a guard. That hook runs after every render, and your assignment to a field can trigger another render. The result is a loop of server calls.
Same method, two ways to call
A method with cacheable=true can be used with @wire and imperatively. A method that changes data (DML) cannot be cacheable, so it can only be called imperatively. The updateEmail method from the controller is an example:
import updateEmail from '@salesforce/apex/ContactController.updateEmail';
async function save(contactId, email) {
await updateEmail({ contactId, email });
}The method returns void, so the awaited value is undefined. Resolution of the Promise is the success signal.
Common mistakes
- Forgetting
awaitor.then.this.contacts = searchContacts(...)assigns a Promise, not an array. The template then renders nothing useful. - Calling the import as if it were a Promise.
searchContactsis a function. WritesearchContacts(...), with parentheses, even when there are no parameters. - Assuming the call is instant. The network round trip takes time, so the field keeps its old value until the Promise resolves.
- Calling a method that is not
@AuraEnabledor notpublic/globalandstatic. The import then fails at deployment or the call fails at run time.
Exercise
A developer writes this.contacts = searchContacts({ searchTerm: this.searchTerm }); in a click handler, without await. What does this.contacts hold, and how do you fix the line?
Show answer
It holds a Promise object, not the list of contacts. Mark the handler async and write this.contacts = await searchContacts({ searchTerm: this.searchTerm });, or use searchContacts({ ... }).then(result => { this.contacts = result; }).