Sub topic 8
Showing a message when the list is empty
This chapter assumes you can write a basic LWC template and class, bind properties with curly braces, and use for:each with a key. It also assumes you know lwc:if and lwc:else. Here you will add the missing piece: what the user sees when the array has no items.
Why an empty list needs its own markup
An empty array renders nothing. for:each produces zero <li> elements, and the <ul> around them stays on the page as an empty element. The user sees a blank area and cannot tell whether the data is still loading, the search found nothing, or the component is broken.
Two things follow from this:
- The template must decide between "show the list" and "show a fallback message".
- That decision needs a boolean, and LWC templates cannot calculate one for you.
Templates cannot run expressions
An LWC template only accepts a property or getter name inside the curly braces. It does not accept comparisons, negation, or method calls. These all fail to compile or do not work:
<!-- None of these are valid LWC template syntax -->
<ul lwc:if={contacts.length > 0}>
<ul lwc:if={!isEmpty}>
<ul lwc:if={contacts.length}>The fix is a getter in the JavaScript class. The getter holds the logic, and the template binds to its name.
get hasContacts() {
return Array.isArray(this.contacts) && this.contacts.length > 0;
}The Array.isArray check matters. Data often starts as undefined and becomes an array later, for example before a wire service or an imperative Apex call returns. Reading .length on undefined throws a TypeError during render and the component fails to display. The Array.isArray check returns false for both undefined and null, so the getter is safe in every state.
The basic pattern: lwc:if and lwc:else
Pair the list with a fallback element using lwc:if and lwc:else. Only one of the two renders at a time.
<template>
<ul lwc:if={hasContacts}>
<template for:each={contacts} for:item="contact">
<li key={contact.Id}>{contact.Name}</li>
</template>
</ul>
<p lwc:else>No contacts to show.</p>
</template>Rules for the pair:
lwc:elsemust be the next sibling element after thelwc:ifelement. Another element between them breaks the chain and the template fails to compile.- The directive goes on one element. To switch several elements together, put the directive on a wrapper
<template>tag, which adds nothing to the DOM, as in<template lwc:if={hasContacts}>. - The
keystill goes on the first element inside thefor:eachloop, exactly as in earlier chapters. The empty check does not change that rule.
Older syntax you may see
Older components use if:true and if:false instead. They still work, but the lwc:if, lwc:elseif and lwc:else family is the current form, and you should not mix the two styles on the same element. if:false={hasContacts} is also the only old way to express "not". With lwc:else you no longer need a second getter for the negative case.
Distinguishing three states: loading, empty, and has data
A fallback message that says "No contacts to show" is wrong while data is still loading. A user who sees it for half a second and then sees a list loses trust in the page. Real components usually have three states:
| State | `contacts` value | What to show |
|---|---|---|
| Loading | `undefined` (not set yet) | A loading message or spinner |
| Loaded, no results | `[]` | The empty-state message |
| Loaded, with results | `[{...}, ...]` | The list |
lwc:elseif lets you chain all three. Here is a complete component you can paste into an org or a local LWC project.
<!-- contactList.html -->
<template>
<p lwc:if={isLoading}>Loading contacts...</p>
<ul lwc:elseif={hasContacts}>
<template for:each={contacts} for:item="contact">
<li key={contact.Id}>{contact.Name}</li>
</template>
</ul>
<p lwc:else>No contacts to show.</p>
<button onclick={handleLoad}>Load contacts</button>
<button onclick={handleClear}>Clear contacts</button>
</template>// contactList.js
import { LightningElement } from 'lwc';
export default class ContactList extends LightningElement {
contacts;
loaded = false;
get isLoading() {
return !this.loaded;
}
get hasContacts() {
return Array.isArray(this.contacts) && this.contacts.length > 0;
}
connectedCallback() {
// Simulate a server call that returns an empty result.
setTimeout(() => {
this.contacts = [];
this.loaded = true;
}, 800);
}
handleLoad() {
this.contacts = [
{ Id: '003A', Name: 'Amy Taylor' },
{ Id: '003B', Name: 'Ravi Patel' }
];
this.loaded = true;
}
handleClear() {
this.contacts = [];
}
}Walk through what happens:
- On first render,
loadedisfalse, soisLoadingistrueand the loading text shows. - After 800 ms,
contactsbecomes[]andloadedbecomestrue.isLoadingis nowfalse,hasContactsisfalse, so thelwc:elsemessage appears. - Clicking Load contacts assigns a new array with two objects.
hasContactsbecomestrueand the list renders. - Clicking Clear contacts assigns
[]again and the message comes back.
Each state change works because the component assigns a new value to a field. The getters are recomputed on the next render, so the template always reflects the current array.
Choosing a good empty-state message
The message is part of the interface, so write it for the user's situation:
- Say what is missing: "No contacts to show." is better than "Nothing here."
- If a filter caused the emptiness, say so: "No contacts match 'Taylor'." A user who sees only "No contacts" may think the data is gone.
- Offer a next step when one exists, such as a button to add the first record.
A filtered example needs a second getter that holds the current search text, but the template pattern stays the same. Keep the filtering in JavaScript, produce an array, and let hasContacts check that array. Do not check the unfiltered array, or the message will never appear when a filter removes every row.
get visibleContacts() {
const term = (this.searchTerm || '').toLowerCase();
return (this.contacts || []).filter((contact) =>
contact.Name.toLowerCase().includes(term)
);
}
get hasVisibleContacts() {
return this.visibleContacts.length > 0;
}The template then loops over visibleContacts and tests hasVisibleContacts.
What for:each does with undefined or null
If you pass undefined or null straight to for:each, the loop renders nothing, so the page does not crash. In development mode the engine can log an error to the browser console saying the value must be an array or iterable. That log is noise you should not ship. Guarding with lwc:if={hasContacts} keeps the loop from receiving a non-array in the first place.
A related trap is a non-array object. A for:each over a plain object with no iterator fails the same way. If a service returns { records: [...] }, loop over data.records, not over data.
Common mistakes
- Putting an expression in the braces.
lwc:if={contacts.length > 0}does not compile. Use a getter. - Reading
.lengthon a value that may be undefined. The getter throws during render. Check withArray.isArrayfirst. - Mutating the array and expecting a refresh. Calling
this.contacts.push(item)on a plain field may not update the view. Assign a new array:this.contacts = [...this.contacts, item]. The "Updating a list" chapter covers this in depth. - Placing an element between
lwc:ifandlwc:else. The compiler rejects the template because the chain is broken. Keep the elements adjacent, or wrap the whole group. - Showing "empty" while loading. Track a separate loading flag, or keep the array
undefineduntil the data arrives, and add alwc:ifbranch for that state. - Testing the wrong array. If you filter the data, test the filtered result, not the source array.
Summary of the pattern
- Compute a boolean in a getter. The template cannot do it for you.
- Guard against non-array values with
Array.isArray. - Put
lwc:ifon the list container andlwc:elseon the message, adjacent to each other. - Add
lwc:elseifwhen you need a separate loading state. - Update the list by assigning a new array so the getter reruns.
Exercise
A component has contacts set to undefined until a server call returns. The template uses <ul lwc:if={contacts.length}> and a <p lwc:else> message. Name the two problems with this template and write the replacement getter and template lines.
Show answer
First, lwc:if cannot take an expression such as contacts.length. It accepts only a property or getter name. Second, even as a getter body, reading .length on undefined throws a TypeError during render. Replacement getter: get hasContacts() { return Array.isArray(this.contacts) && this.contacts.length > 0; }. Replacement template: <ul lwc:if={hasContacts}>...</ul> followed immediately by <p lwc:else>No contacts to show.</p>.
Exercise
You add a search box that filters the list. Users type "zzz" and see a blank area instead of the empty message. The getter is get hasContacts() { return this.contacts.length > 0; } and the loop runs over visibleContacts. What is wrong, and how do you fix it?
Show answer
The getter checks the unfiltered contacts array, which still has items, so the list branch renders with zero visible rows. Check the filtered array instead: get hasVisibleContacts() { return this.visibleContacts.length > 0; }, and bind lwc:if to hasVisibleContacts. A message such as "No contacts match your search." then appears when the filter removes every row.
Exercise
Why does the three-state example use lwc:elseif rather than two separate lwc:if blocks?
Show answer
The chain guarantees that exactly one branch renders. With separate lwc:if blocks you would need to write each condition so they never overlap, for example making the empty message conditional on both "loaded" and "no items". The chain keeps the order clear (loading, then list, then empty) and avoids showing two states at once during a transition.