Sub topic 10
Worked example: a loading, error, and ready panel
This chapter builds a small status panel that shows a loading message, an error message with a retry button, or the loaded data. It assumes you can read an LWC template and class, know how to bind properties with curly braces, and understand that class fields are reactive. It also assumes you know how lwc:if, lwc:elseif, and lwc:else chain together. The goal is to see how those pieces work together when one piece of state drives the whole UI.
The idea: one state, one visible branch
Many components load something and then show it. At any moment the component is in exactly one of three situations:
- It is waiting for data.
- The request failed.
- The data arrived.
A common first attempt is to keep three separate booleans, such as isLoading, hasError, and isReady. That lets the component reach impossible combinations, such as loading and error both being true. A better model is a single status field with a fixed set of values. Only one value can be held at a time, so only one branch can render.
The diagram shows the states and the transitions this chapter implements.
The template
The template uses a three-branch chain. The first branch is lwc:if, the middle is lwc:elseif, and the last is lwc:else.
<template>
<template lwc:if={isLoading}>
<p>Loading...</p>
</template>
<template lwc:elseif={hasError}>
<p>Something went wrong.</p>
<button onclick={handleRetry}>Retry</button>
</template>
<template lwc:else>
<p>Data is ready.</p>
</template>
</template>Three details matter here:
- The three
<template>tags are siblings with nothing between them. That adjacency is what links them into one chain. lwc:elsehas no value. Writinglwc:else={something}is an error.- Each branch contains its own content. The loading branch holds only a paragraph. The error branch holds a paragraph and a button. When the error branch renders, the button exists in the DOM. When it does not, the button does not exist at all.
The wrapper <template> tag is used because the error branch needs two elements, and a <template> tag does not add an extra element to the DOM. If a branch needs only one element, you can put the directive on that element directly, as a later section shows.
The class
lwc:if and lwc:elseif accept only a simple property reference, not an expression. You cannot write lwc:if={status === 'loading'}. Getters convert the comparison into a property that the template can read.
import { LightningElement } from 'lwc';
export default class StatusPanel extends LightningElement {
status = 'loading';
get isLoading() {
return this.status === 'loading';
}
get hasError() {
return this.status === 'error';
}
handleRetry() {
this.status = 'loading';
}
}Notice what is not here. There is no isReady getter, because the lwc:else branch covers every status that is neither loading nor error. That is the main benefit of the final fallback: you do not need to write a condition for it.
Why changing `status` updates the DOM
Class fields in LWC are reactive. When the template reads isLoading, the getter reads this.status, so the engine records that the template depends on status. When handleRetry assigns 'loading' to this.status, the engine schedules a re-render. During the re-render, the chain is evaluated again from the top, and exactly one branch is produced.
The evaluation order is:
- Read
isLoading. If it is truthy, render the first branch and stop. - Otherwise, read
hasError. If it is truthy, render the second branch and stop. - Otherwise, render the
lwc:elsebranch.
Because evaluation stops at the first truthy branch, the order of branches matters. If two conditions could be true at once, the earlier one wins.
Making it do something
The panel above never leaves the loading state, because nothing changes status besides the retry handler. A realistic component loads data when it is added to the page. This version simulates a request and moves between the three states. It also stores the loaded value so the ready branch can display it.
import { LightningElement } from 'lwc';
export default class StatusPanel extends LightningElement {
status = 'loading';
items = [];
connectedCallback() {
this.load();
}
get isLoading() {
return this.status === 'loading';
}
get hasError() {
return this.status === 'error';
}
get itemCount() {
return this.items.length;
}
async load() {
this.status = 'loading';
try {
this.items = await this.fetchItems();
this.status = 'ready';
} catch (e) {
this.status = 'error';
}
}
fetchItems() {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() < 0.5) {
resolve(['Alpha', 'Beta', 'Gamma']);
} else {
reject(new Error('Network failure'));
}
}, 1000);
});
}
handleRetry() {
this.load();
}
}The matching template displays the count in the ready branch.
<template>
<template lwc:if={isLoading}>
<p>Loading...</p>
</template>
<template lwc:elseif={hasError}>
<p>Something went wrong.</p>
<button onclick={handleRetry}>Retry</button>
</template>
<template lwc:else>
<p>Loaded {itemCount} items.</p>
</template>
</template>The component sets status at each step of the request. Each assignment is a change the engine can observe, so the visible branch follows the state without any code that touches the DOM directly.
Using the directive on an element
When a branch contains a single element, the wrapper tag is optional. You can put the directives directly on the element.
<template>
<p lwc:if={hasItems}>You have {itemCount} items.</p>
<p lwc:else>Your list is empty.</p>
</template>This form is shorter, but the loading, error, and ready panel needs the wrapper for its error branch, since that branch holds two elements. You can mix both forms in one chain, as long as the branches stay adjacent siblings.
Extending the panel safely
Adding a fourth state shows how the pattern scales. Suppose you want an empty state for a successful request that returned no rows. Add a getter and insert a branch before the fallback.
get isEmpty() {
return this.status === 'ready' && this.items.length === 0;
}<template lwc:elseif={isEmpty}>
<p>No items found.</p>
</template>Place this branch after the error branch and before lwc:else. The lwc:else branch then covers only a ready state with data. Keeping the fallback as the "normal" case means any status value you forget to handle appears as the normal view, so write a test for each status if you add more values.
Common mistakes in this example
| Mistake | Result | Fix |
|---|---|---|
| Writing `lwc:if={status === 'loading'}` | Template compile error, since expressions are not allowed | Move the comparison into a getter |
| Writing `lwc:else={isReady}` | Compile error, since `lwc:else` takes no value | Write `lwc:else` alone |
| Putting a `<div>` between the `lwc:if` and `lwc:elseif` templates | The chain is broken and the `lwc:elseif` fails to compile | Keep branches adjacent siblings |
| Forgetting to reset `status` before a retry | The error message stays visible while the new request runs | Set `status = 'loading'` at the start of `load` |
| Updating a non-reactive value, such as a variable outside the class | The UI does not re-render | Store state in a class field |
Exercises
Exercise
In the extended panel, status is 'ready' and items is an empty array. The chain is lwc:if={isLoading}, lwc:elseif={hasError}, lwc:elseif={isEmpty}, lwc:else. Which branch renders, and why does the order of the hasError and isEmpty branches not change the result here?
Show answer
The isEmpty branch renders, showing "No items found." isLoading is false because the status is not 'loading'. hasError is false because the status is not 'error'. isEmpty is true because the status is 'ready' and the array is empty. The order of hasError and isEmpty does not matter here because their conditions cannot both be true. They test different status values. Order matters only when two conditions can be true at the same time.
Exercise
A teammate writes <template lwc:if={isLoading}>...</template>, then a <p> with a divider, then <template lwc:else>...</template>. The build fails. What is wrong, and how do you fix it?
Show answer
The <p> element sits between the lwc:if template and the lwc:else template, so the two are no longer adjacent siblings and the chain is broken. The lwc:else has no lwc:if directly before it. Move the divider before the lwc:if or after the lwc:else, or place it inside one of the branches.