Sub topic 6
Showing a loading state
An imperative Apex call is asynchronous. Between the click and the response, the component has nothing new to show, and the user can't tell whether the click registered. This chapter covers how to track that waiting period, display it, and keep it correct when calls fail, overlap, or finish quickly.
It assumes you can already call an Apex method imperatively with await or .then(), and that you know how class fields drive rendering in a Lightning Web Component template.
Why a loading flag is needed
An imperative call returns a Promise. The Promise is pending for the length of a server round trip, which can be tens of milliseconds or several seconds. During that time:
- The user may click the button again and start duplicate calls.
- The list may show stale results with no sign they are about to change.
- An empty list is ambiguous. It could mean "no matches" or "still waiting".
The fix is a boolean field that is true while a call is in flight. The template reads it to show a spinner, disable controls, and hold back the "no results" message.
The basic pattern
Set the flag before the call. Clear it in a finally block so it is reset on both success and failure.
import { LightningElement } from 'lwc';
import searchContacts from '@salesforce/apex/ContactController.searchContacts';
export default class ContactSearch extends LightningElement {
searchTerm = '';
contacts = [];
errorMessage;
isLoading = false;
hasSearched = false;
handleTermChange(event) {
this.searchTerm = event.target.value;
}
async handleSearch() {
this.isLoading = true;
this.errorMessage = undefined;
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;
this.hasSearched = true;
}
}
get hasNoResults() {
return this.hasSearched && !this.isLoading && !this.errorMessage && this.contacts.length === 0;
}
}The order matters. If you reset isLoading only at the end of the try block, any exception skips that line and the spinner never goes away. The finally block runs in every case, so it is the right place for cleanup.
The same logic with then/catch/finally looks like this:
handleSearch() {
this.isLoading = true;
searchContacts({ searchTerm: this.searchTerm })
.then((result) => {
this.contacts = result;
})
.catch((error) => {
this.contacts = [];
this.errorMessage = error?.body?.message || 'Unknown error';
})
.finally(() => {
this.isLoading = false;
});
}Both forms behave the same. Pick one per component and stay consistent.
Rendering the state in the template
The template uses lwc:if to show the spinner, and a getter to disable the button while a call is running.
<template>
<lightning-card title="Contact Search">
<div class="slds-p-around_medium slds-is-relative" aria-busy={isLoading}>
<lightning-input label="Name" value={searchTerm} onchange={handleTermChange}></lightning-input>
<lightning-button
label="Search"
onclick={handleSearch}
disabled={isLoading}
></lightning-button>
<template lwc:if={isLoading}>
<lightning-spinner alternative-text="Loading contacts" size="small"></lightning-spinner>
</template>
<template lwc:elseif={errorMessage}>
<p class="slds-text-color_error">{errorMessage}</p>
</template>
<template lwc:elseif={hasNoResults}>
<p>No contacts match that name.</p>
</template>
<template lwc:else>
<template for:each={contacts} for:item="contact">
<p key={contact.Id}>{contact.Name} ({contact.Email})</p>
</template>
</template>
</div>
</lightning-card>
</template>Four details are worth knowing:
lightning-spinneris positioned absolutely. It fills the nearest ancestor that hasposition: relative. Theslds-is-relativeclass on the wrapper keeps the spinner inside the component instead of covering the whole page.alternative-textis the text a screen reader announces. It is required for accessibility, so make it specific.aria-busy={isLoading}tells assistive technology that the region is updating.- The
lwc:if/lwc:elseif/lwc:elsechain makes the four states mutually exclusive: loading, error, empty, and results.
The lifecycle as a state machine
The component moves through a small set of states. Naming them helps you spot gaps, such as a path that never leaves Loading.
Every arrow leaving Loading must be covered by your code. The finally block guarantees that both exits clear the flag.
Overlapping calls
Disabling the button prevents double clicks from that button. It does not cover every trigger. If the search also runs on each keystroke or from a parent component, two calls can be in flight at once, and responses can arrive out of order. The slower, older response then overwrites the newer one, and the first call to finish clears the spinner while the second is still running.
A request counter solves both problems. Each call takes a number, and only the latest call may update state.
import { LightningElement } from 'lwc';
import searchContacts from '@salesforce/apex/ContactController.searchContacts';
export default class ContactSearchLive extends LightningElement {
searchTerm = '';
contacts = [];
errorMessage;
isLoading = false;
latestRequestId = 0;
async runSearch() {
const requestId = ++this.latestRequestId;
this.isLoading = true;
this.errorMessage = undefined;
try {
const result = await searchContacts({ searchTerm: this.searchTerm });
if (requestId !== this.latestRequestId) {
return; // a newer call exists, so discard this result
}
this.contacts = result;
} catch (error) {
if (requestId !== this.latestRequestId) {
return;
}
this.contacts = [];
this.errorMessage = error?.body?.message || error?.message || 'Unknown error';
} finally {
if (requestId === this.latestRequestId) {
this.isLoading = false;
}
}
}
}A return inside try or catch still runs finally, so the guard in finally is what keeps an old call from clearing the flag early.
Apex cannot cancel the older request. It still runs on the server and counts against limits. The counter only stops its result from reaching the UI. Reducing the number of calls is a separate topic, covered in the chapter on avoiding unnecessary calls.
Several calls at once
When a component starts independent calls, for example one for contacts and one for accounts, a single boolean breaks down. Use a counter of pending calls and derive the flag from it.
import { LightningElement } from 'lwc';
import getContacts from '@salesforce/apex/DashboardController.getContacts';
import getAccounts from '@salesforce/apex/DashboardController.getAccounts';
export default class Dashboard extends LightningElement {
contacts = [];
accounts = [];
pendingCalls = 0;
get isLoading() {
return this.pendingCalls > 0;
}
async track(promise) {
this.pendingCalls++;
try {
return await promise;
} finally {
this.pendingCalls--;
}
}
async connectedCallback() {
const [contacts, accounts] = await Promise.all([
this.track(getContacts()),
this.track(getAccounts())
]);
this.contacts = contacts;
this.accounts = accounts;
}
}The spinner stays visible until the last call settles. If either call rejects, Promise.all rejects too. Add a try/catch around it in real code, as shown in the error handling chapter.
Choosing an approach
| Situation | Approach | Watch out for |
|---|---|---|
| One button, one call | Boolean flag with `finally` | Forgetting `finally` |
| Call can be triggered several ways | Boolean flag plus request counter | Stale results overwriting new ones |
| Several independent calls | Pending-call counter with a getter | Counter never decremented on error |
| Very fast calls | Boolean flag, optionally a minimum display time | Spinner flicker |
Edge cases
- Flicker. If the response takes 40 ms, the spinner appears and vanishes almost instantly, which looks like a glitch. Either delay showing the spinner by about 200 ms, or keep it visible for a minimum time. Many components skip this and accept the flicker. Add it only if testing shows a problem.
- Component removed mid-call. If the user navigates away, the Promise still resolves and your code sets fields on a disconnected component. This is harmless in LWC, but avoid follow-up work such as dispatching events in that case.
- First load. For data needed at render time,
isLoadingshould start astrue, or the template briefly shows the "no results" message before the call begins. In the examples above,hasSearchedprevents that message from showing before the first search. - Partial failure. If a call fails, clear stale data (
this.contacts = []) or label it clearly. Showing old rows beside an error message misleads users.
Exercise
A component calls an Apex method on every keystroke and sets isLoading = false at the end of the try block. Users report two problems: the spinner sometimes disappears while a request is still running, and sometimes the list shows results for an older search term. Name the cause of each problem and the change that fixes both.
Show answer
The spinner disappears because the first call to finish clears the shared flag even though a later call is still pending. The old results appear because responses can arrive out of order, so a slow earlier call overwrites a newer result. Fix both by giving each call an incrementing request ID, ignoring any result whose ID is not the latest, and clearing isLoading in a finally block only when the ID matches the latest one. The finally block also stops the spinner from sticking when a call throws.
Exercise
Why does a lightning-spinner sometimes cover the entire page instead of just your component, and how do you fix it?
Show answer
The spinner is positioned absolutely and fills its nearest ancestor with position: relative. If no ancestor in your template has that, it fills a much larger container. Wrap the content in an element with the slds-is-relative class so the spinner stays inside it.