Sub topic 6
Showing a loading state
This chapter assumes you can write a basic LWC with a click handler, and that you know async/await and try/catch/finally. It also assumes you have a @AuraEnabled method imported as in the earlier chapters. Here you add feedback while the server call is running.
Why a loading state matters
An imperative Apex call takes time. It crosses the network, runs the query, and returns. During that wait the component shows its old data, and nothing tells the user that anything is happening. Users click again, and each click sends another request.
A loading state is a boolean field on the component. You set it to true before the call and back to false when the call ends. The template reads that field to show a spinner and to disable controls.
The loading flag
In LWC, class fields are reactive. When isLoading changes, the template re-renders. The pattern has three steps:
- Set
isLoading = truebefore the call. - Await the Promise.
- Set
isLoading = falsein afinallyblock.
import { LightningElement } from 'lwc';
import searchContacts from '@salesforce/apex/ContactController.searchContacts';
export default class ContactSearch extends LightningElement {
searchTerm = '';
contacts = [];
errorMessage;
isLoading = false;
handleTermChange(event) {
this.searchTerm = event.target.value;
}
async handleSearch() {
if (this.isLoading) {
return;
}
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;
}
}
}The finally block runs whether the call succeeds or throws. If you reset the flag only in the success path, one failed call leaves the spinner on forever.
The early if (this.isLoading) return; ignores clicks while a request is in flight. It is a cheap guard against duplicate calls.
Reading the flag in the template
<template>
<lightning-card title="Contact Search">
<div class="slds-p-around_medium">
<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"></lightning-spinner>
</template>
<template for:each={contacts} for:item="contact">
<p key={contact.Id}>{contact.Name} ({contact.Email})</p>
</template>
</div>
</lightning-card>
</template>lightning-spinner fills its nearest positioned container. Inside lightning-card it covers the card body. Always set alternative-text, because screen readers announce it.
The state cycle
The component moves through a small set of states. The flag is true only in one of them.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Resetting the flag only after `await` in the success path | Spinner stays on after an error | Use `finally` |
| Not disabling the trigger | Duplicate requests | Use `disabled={isLoading}` or an early return |
| Forgetting to clear the old error | A stale message shows during the next call | Set `errorMessage = undefined` before the call |
| Using one flag for several independent calls | The first call to finish hides the spinner too early | Use one flag per call, or a counter |
Choosing what to show
A spinner suits short waits. For a first load of a large list, consider hiding the empty list until the first response arrives. Otherwise users briefly see "no results", which is wrong information. A separate hasSearched flag set in finally handles this.
Exercise
A component sets isLoading = true, awaits an Apex call, then sets isLoading = false on the next line after the await. The Apex method throws an exception. What does the user see, and how do you fix it?
Show answer
The await throws, so the line that resets isLoading never runs, and the spinner stays on. Wrap the call in try/catch/finally and set isLoading = false in the finally block, which runs on both success and failure.