Sub topic 13
Avoiding unnecessary or repeated calls
This chapter assumes you can already call an Apex method imperatively, handle its Promise, and manage a loading flag. Each imperative call is a network round trip to the server. It also counts against Salesforce governor limits, such as the number of concurrent long-running requests and the limits for each Apex transaction. Components that call Apex on every keystroke or button click can feel slow and waste server capacity.
Where repeated calls come from
Three patterns cause most unnecessary calls:
- Calling on every
changeevent of a text input, so typing "Lovelace" sends eight requests. - Letting a user click a button again while the first call is still running.
- Calling Apex again for data the component already holds, for example after a re-render or when the same search term is repeated.
Guard against double submission
The loading flag you already keep can also block repeat calls. Return early if a request is in flight, and disable the button in the template.
async handleSearch() {
if (this.isLoading) {
return;
}
this.isLoading = true;
try {
this.contacts = await searchContacts({ searchTerm: this.searchTerm });
} catch (error) {
this.contacts = [];
this.errorMessage = error?.body?.message || error?.message || 'Unknown error';
} finally {
this.isLoading = false;
}
}<lightning-button label="Search" onclick={handleSearch} disabled={isLoading}></lightning-button>Debounce typing
Debouncing waits until the user pauses before it sends a call. Each new keystroke cancels the pending timer and starts a new one.
import { LightningElement } from 'lwc';
import searchContacts from '@salesforce/apex/ContactController.searchContacts';
const DELAY_MS = 300;
export default class ContactTypeahead extends LightningElement {
contacts = [];
errorMessage;
delayTimeout;
handleTermChange(event) {
const term = event.target.value;
clearTimeout(this.delayTimeout);
this.delayTimeout = setTimeout(() => this.runSearch(term), DELAY_MS);
}
async runSearch(term) {
try {
this.contacts = await searchContacts({ searchTerm: term });
} catch (error) {
this.contacts = [];
this.errorMessage = error?.body?.message || error?.message || 'Unknown error';
}
}
disconnectedCallback() {
clearTimeout(this.delayTimeout);
}
}Clearing the timer in disconnectedCallback stops a call from firing after the component is removed from the page.
Ignore stale responses
Responses can arrive out of order. If the call for "Ada" returns after the call for "Adam", the older result would overwrite the newer one. Keep a request counter and apply only the latest response.
requestId = 0;
async runSearch(term) {
const current = ++this.requestId;
try {
const result = await searchContacts({ searchTerm: term });
if (current === this.requestId) {
this.contacts = result;
}
} catch (error) {
if (current === this.requestId) {
this.contacts = [];
this.errorMessage = error?.body?.message || error?.message || 'Unknown error';
}
}
}Skip calls that cannot return useful data
Check the input before you call. An empty or very short term often matches too much or nothing at all.
if (!term || term.trim().length < 2) {
this.contacts = [];
return;
}Keep the same rule in Apex. The client check saves a round trip, but only server code can be trusted, so the controller should still limit its results with LIMIT.
Reuse data you already have
If the user repeats a search, you can return a stored result instead of calling again. A simple Map keyed by the search term works for data that rarely changes.
cache = new Map();
async lookup(term) {
if (this.cache.has(term)) {
return this.cache.get(term);
}
const result = await searchContacts({ searchTerm: term });
this.cache.set(term, result);
return result;
}Clear the map after any change that could make results stale, such as a successful update. For read-only methods, cacheable=true also lets the platform reuse results, as covered in the earlier chapter on that option.
Summary of techniques
| Problem | Technique |
|---|---|
| Button clicked twice | Return early while `isLoading` is true and disable the button |
| Call on every keystroke | Debounce with `setTimeout` and `clearTimeout` |
| Older response overwrites newer one | Compare a request counter |
| Pointless short or empty input | Validate before calling |
| Same query repeated | Store results in a `Map` and clear it after changes |
Exercise
A user types "Smith" quickly into a search box that calls Apex on every change event. Two problems appear: five calls are sent, and sometimes the results for "Smit" replace the results for "Smith". Which two techniques fix these problems?
Show answer
Debounce the input handler so only one call is sent after the user pauses. Add a request counter and apply a response only if it belongs to the latest request, so a slow older response cannot overwrite a newer one.