Module 05 · Lesson 5.4
Loading, Empty and Error States
On this page
- What you will learn
- Why every screen has more than one state
- Writing loading, empty and error messages people can act on
- StatusMessage and ProblemMessage: small components for every state
- Worked scenario: Tidewell's free-slot screen in every state
- Step-by-step workflow
- What the assistant can and cannot do for states and messages
- Conclusion and your next step
- Reusable prompt
- Expected output
- Common errors and fixes
- Validation checklist
- Hands-on exercise
- Knowledge check
- Frequently asked questions
- References
Picture a shop with a closed door and no sign. Is it shut for the day, being restocked or out of business? You do not know, so you walk away. A screen that is blank while it loads, or silent when it fails, treats people the same way.
In this lesson you give every Tidewell screen a clear answer to 'what is happening now?'. You model the states with one TypeScript type, write messages people can act on, and build small components that show each state. You then render every state to HTML and read it, so you know what each person would see.
What you will learn
- Model loading, empty, error and ready as one TypeScript union that cannot be half-set.
- Write messages that say what happened, what is safe and what to do next.
- Build small components that show each state, and render them to check the output.
- Handle a conflict, such as a taken slot, as its own state with its own message.
Before you start
- Completed Calling the API from the Frontend, or have an API client of your own.
- Access to any capable AI assistant.
- Optional: Node.js and the project from earlier lessons, if you want to run the examples.
Why every screen has more than one state
A screen that loads data is in one of a few situations at any moment. It is waiting. It has data. It has found nothing. Or it has failed. If your code handles only 'has data', the other three show up as a blank page, a spinner that never ends or a crash.
- Loading state
- The data has been asked for and has not arrived. Like a queue at a counter: you are told someone is working on it.
- Empty state
- The request worked, and there is nothing to show. Like an empty shelf with a note that says 'more stock on Monday'.
- Error state
- The request failed. Like a sign on a lift: out of order, use the stairs.
- Conflict state
- The request was understood but clashes with a change made meanwhile, such as someone else booking the slot first.
- Union type
- A TypeScript type that says a value is exactly one of several named shapes. Like a traffic light: red, amber or green, never two at once.
A union type is the right tool because it makes impossible mixes impossible. A screen cannot be 'loading' and 'ready' at once, and it cannot be 'ready' without data. TypeScript checks this for you.
export type LoadState<T> =
| { status: "loading" }
| { status: "empty" }
| { status: "error"; problem: Problem }
| { status: "ready"; data: T };
export type SubmitState =
| { status: "idle" }
| { status: "submitting" }
| { status: "success"; booking: Booking }
| { status: "conflict"; problem: Problem }
| { status: "error"; problem: Problem };The states for loading a list, and for submitting a form. Each has a status word and only the data it needs.
What each part does
statusis the tag that tells the shapes apart. Checkingstate.status === "ready"lets TypeScript knowstate.dataexists.loadingandemptycarry nothing, because nothing is needed to describe them.errorcarries theProblemfrom the API client, so the message can depend on what went wrong.SubmitStateaddssubmitting,successandconflictfor forms. A 409slot-takenreply becomesconflict.
Writing loading, empty and error messages people can act on
A good message answers three questions. What happened? Is anything at risk? What can I do now? Keep it short, use plain words and do not blame the person. Never show codes, stack traces or raw server text.
| Situation | A weak message | A better message |
|---|---|---|
| Free times are loading | (blank) | Loading free times |
| No free times that day | No data | No free times on this date. Try another date, or phone the clinic on 01632 960 123. |
| The connection fails | Error: Failed to fetch | We could not reach the booking system. Check your connection and try again. |
| The slot was just taken | 409 Conflict | That time has just been taken. Please choose another time from the list. |
| Inside the notice period | Forbidden | Use the server's message, which tells the patient to phone the clinic and gives the opening hours. |
| Something broke on the server | Internal Server Error | Something went wrong on our side. Quote the reference if you phone the clinic. |
Notice the connection message. For a booking or cancellation, a failed connection does not prove that nothing happened. The request may have arrived before the connection dropped. So the message tells the person to look at My bookings first.
Screen readers need to hear changes too. A message with role="status" is announced politely, when the reader is free. A message with role="alert" interrupts, so use it only for errors. The next lessons return to this.
StatusMessage and ProblemMessage: small components for every state
Two small components do most of the work. StatusMessage shows a title and optional extra content, with a tone: info, success or error. ProblemMessage turns a Problem into the right words.
import type { ReactNode } from "react";
export type Tone = "info" | "success" | "error";
export function StatusMessage({ tone, title, children }: { tone: Tone; title: string; children?: ReactNode }) {
const role = tone === "error" ? "alert" : "status";
return (
<div className={"status-message status-" + tone} role={role}>
<p className="status-title">{title}</p>
{children}
</div>
);
}What each part does
tonechooses the look through a class name, and the role through one line: errors getalert, everything else getsstatus.childrenis optional, so a loading message can be a single title.- The class name
status-plus the tone lets one stylesheet colour all three tones, but the title and role carry the meaning, not the colour.
== StatusMessage info ==
<div class="status-message status-info" role="status">
<p class="status-title">Loading free times</p>
</div>
== StatusMessage success ==
<div class="status-message status-success" role="status">
<p class="status-title">Your booking is confirmed</p>
</div>
== StatusMessage error ==
<div class="status-message status-error" role="alert">
<p class="status-title">Something went wrong</p>
<p>Try again.</p>
</div>ProblemMessage reads the last part of the problem's type, such as slot-taken, and picks the words. Here are the first two cases.
import type { Problem } from "../features/bookings/types";
import { problemCode } from "../lib/api-client";
import { StatusMessage } from "./StatusMessage";
export function ProblemMessage({ problem }: { problem: Problem }) {
switch (problemCode(problem)) {
case "network-error":
return (
<StatusMessage tone="error" title="We could not reach the booking system">
<p>Check your connection and try again. If you were booking or cancelling, look at My bookings first.</p>
</StatusMessage>
);
case "slot-taken":
return (
<StatusMessage tone="error" title="That time has just been taken">
<p>Someone else booked it first. Please choose another time from the list.</p>
</StatusMessage>
);The start of the component. Cases for notice-period, not-found, invalid-request and a default follow in the same pattern.
Two cases show the server's own detail. One is the notice period, because the server owns the rule and the phone details. The other is the default case, because a 500 reply carries a short reference. Everything else uses fixed words that the team reviewed. Here is what each case renders.
== ProblemMessage slot-taken ==
<div class="status-message status-error" role="alert">
<p class="status-title">That time has just been taken</p>
<p>Someone else booked it first. Please choose another time from the list.</p>
</div>
== ProblemMessage notice-period ==
<div class="status-message status-error" role="alert">
<p class="status-title">This booking cannot be changed online</p>
<p>This booking starts in less than 24 hours. Please phone the clinic on 01632 960 123, Monday to Friday, 8:00 to 18:00.</p>
</div>
== ProblemMessage network-error ==
<div class="status-message status-error" role="alert">
<p class="status-title">We could not reach the booking system</p>
<p>Check your connection and try again. If you were booking or cancelling, look at My bookings first.</p>
</div>
== ProblemMessage invalid-request ==
<div class="status-message status-error" role="alert">
<p class="status-title">Please check what you entered</p>
<ul>
<li>Choose a date.</li>
</ul>
</div>
== ProblemMessage internal-error ==
<div class="status-message status-error" role="alert">
<p class="status-title">Something went wrong on our side</p>
<p>Please try again. If it keeps happening, quote reference 4F7K2Q when you phone the clinic.</p>
</div>Worked scenario: Tidewell's free-slot screen in every state
Now put the states together. LoadStateView takes a LoadState and shows the right thing for each case. The ready case is a function, so the same view serves any list: free slots, bookings or clinicians.
import type { ReactNode } from "react";
import type { LoadState } from "../features/bookings/types";
import { ProblemMessage } from "./ProblemMessage";
import { StatusMessage } from "./StatusMessage";
interface LoadStateViewProps<T> {
state: LoadState<T>;
loadingText: string;
emptyTitle: string;
emptyHelp: string;
renderReady: (data: T) => ReactNode;
}
export function LoadStateView<T>({ state, loadingText, emptyTitle, emptyHelp, renderReady }: LoadStateViewProps<T>) {
switch (state.status) {
case "loading":
return <StatusMessage tone="info" title={loadingText} />;
case "empty":
return (
<StatusMessage tone="info" title={emptyTitle}>
<p>{emptyHelp}</p>
</StatusMessage>
);
case "error":
return <ProblemMessage problem={state.problem} />;
case "ready":
return <>{renderReady(state.data)}</>;
}
}The switch covers all four statuses. If you add a fifth state later and forget it here, TypeScript reports that the function does not always return a value. That is a useful alarm. Here is what each state renders for S1, with the same free slots as before.
== LoadStateView loading ==
<div class="status-message status-info" role="status">
<p class="status-title">Loading free times</p>
</div>
== LoadStateView empty ==
<div class="status-message status-info" role="status">
<p class="status-title">No free times on this date</p>
<p>Try another date, or phone the clinic on 01632 960 123.</p>
</div>
== LoadStateView error ==
<div class="status-message status-error" role="alert">
<p class="status-title">We could not reach the booking system</p>
<p>Check your connection and try again. If you were booking or cancelling, look at My bookings first.</p>
</div>
== LoadStateView ready ==
<ul class="slot-list">
<li>
<time dateTime="2026-12-01T09:00:00Z">09:00</time> to 09:45</li>
<li>
<time dateTime="2026-12-01T10:00:00Z">10:00</time> to 10:45</li>
<li>
<time dateTime="2026-12-01T11:00:00Z">11:00</time> to 11:45</li>
</ul>No state is blank. The first three tell the person what is going on. The last shows the list. Now see the client component that moves between them. It type-checks, and its rendering comes from the pieces above.
export function FreeSlotsScreen({ client, clinicianId, date }: FreeSlotsScreenProps) {
const [slots, setSlots] = useState<LoadState<FreeSlot[]>>({ status: "loading" });
const [submit, setSubmit] = useState<SubmitState>({ status: "idle" });
const [formErrors, setFormErrors] = useState<FieldError[]>([]);
const [reloads, setReloads] = useState(0);
useEffect(() => {
let ignore = false;
setSlots({ status: "loading" });
client.getFreeSlots(clinicianId, date).then((result) => {
if (!ignore) setSlots(toLoadState(result));
});
return () => {
ignore = true;
};
}, [client, clinicianId, date, reloads]);
function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const slotId = Number(new FormData(event.currentTarget).get("slotId"));
if (!slotId) {
setFormErrors([{ field: "slotId", message: "Choose a time before you continue." }]);
return;
}
setFormErrors([]);
setSubmit({ status: "submitting" });
client.createBooking(slotId).then((result) => {
const next = toSubmitState(result);
setSubmit(next);
if (next.status === "error") setFormErrors(next.problem.errors ?? []);
if (next.status === "conflict") setReloads((n) => n + 1);
});
}The state and the loading effect. Its first 17 lines are imports and prop types, left out here.
What each part does
useStatekeeps the two states: the list (loadingat first) and the form (idleat first).useEffectasks the API for slots when the screen opens, and again if the clinician, the date orreloadschanges. React describes this in its guide to synchronizing with effects (opens in a new tab).ignorestops a slow, old reply from overwriting a newer one. The cleanup function sets it when the screen moves on.toLoadStateandtoSubmitStatefrom the last lesson turn each result into a state.- After a
conflict,setReloadsbumps a counter, which re-runs the effect and fetches the current free times.
The rest of the component decides what to draw. After success it shows only the confirmation card. Otherwise it shows the conflict or error message above the list, and LoadStateView for the list itself.
if (submit.status === "success") {
return (
<StatusMessage tone="success" title="Your booking is confirmed">
<BookingCard booking={submit.booking} />
</StatusMessage>
);
}
return (
<section aria-labelledby="free-times">
<h2 id="free-times">Free times</h2>
{(submit.status === "conflict" || submit.status === "error") && formErrors.length === 0 && (
<ProblemMessage problem={submit.problem} />
)}
<LoadStateView
state={slots}
loadingText="Loading free times"
emptyTitle="No free times on this date"
emptyHelp="Try another date, or phone the clinic on 01632 960 123."
renderReady={(data) => (
<SlotChoiceForm slots={data} errors={formErrors} submitting={submit.status === "submitting"} onSubmit={handleSubmit} />
)}
/>
</section>
);Check this against the plan from Planning Screens from Workflows. Loading, empty, error, ready, submitting and conflict for S1 are all handled. Success shows the booking card. The phone number in the empty message comes from the clinic's details, 01632 960 123, and not from the assistant's imagination.
Step-by-step workflow
Step 1: Take the states from your screen plan
Copy the state list of one screen. Each state already has a source: a scenario or an API problem.
What you should see: A list of states with sources for one screen.
Step 2: Model them as one union type
Write a union with a status word per state, carrying only the data that state needs.
What you should see: A type in which impossible mixes cannot be written.
Step 3: Write the messages
For each state write what happened, what is safe and what to do. Check every number and phone detail against the client's decisions.
What you should see: A message table that a non-technical colleague can read.
Step 4: Build the small components
Make a StatusMessage and a ProblemMessage, then one view that switches on the status. Use alert for errors and status for the rest.
What you should see: Components that cover every state, with no blank case.
Step 5: Render every state and read it
Render each state to HTML with sample data. Check text, roles and links.
What you should see: A saved output for each state, and nothing blank.
Step 6: Walk the failure cases
Switch off your network, or use a fake that fails, and use the screen. Check you can always tell what happened.
What you should see: No dead ends.
- State list
From the plan
- Union type
One status each
- Messages
Plain words
- Components
No blank case
- Render and read
Every state
Every state in the plan ends up as a rendered, read message.
What the assistant can and cannot do for states and messages
Assistants are quick at writing state switches and friendly messages. They are less careful about what a message promises. 'Your booking was not changed' sounds kind, and may be false after a timeout.
| Task | Assistant's part | Your part |
|---|---|---|
| Modelling states | Draft the union type from your list. | Check that no state is missing and none is invented. |
| Writing messages | Offer plain-language drafts. | Check what each message promises, and confirm numbers and rules. |
| Building components | Write the switch and the small components. | Check the roles, the labels and that no state renders blank. |
| Testing | Draft render tests for each state. | Read the output yourself and check it would fail if a state broke. |
| Policy wording | Nothing. Mark it as a question. | Ask the role that owns the rule, such as the practice manager. |
Conclusion and your next step
Every screen that loads data has at least four states: loading, empty, error and ready. A union type keeps them honest, small components show them, and rendering each one proves none is blank. Clear messages tell the person what happened, what is safe and what to do.
Your next step: list the states for one of your own screens and render them all. Then continue to Accessibility Basics for Forms, where you make sure everyone can use the form and hear its errors.
For more practice, try the Appointment Booking Portal project. The Backend Error Handling Review prompt is a useful companion, because it shows what the server side of each message looks like.
Reusable prompt
State and message builder
Asks for a state union, a message table and a view component for one screen, and flags any message that claims more than is known.
You are helping me handle the states of one screen. Do not add features, libraries or styling.
Project: Tidewell Physiotherapy booking system (fictional). TypeScript strict, Next.js App Router, React.
Screen S1: choose a clinician and date, then see free slots (FR-01), in a client component.
States: loading, empty (no free times that date), error, ready, submitting and conflict (409 slot-taken).
Existing types: LoadState<T> and SubmitState in src/features/bookings/types.ts. The API client returns { ok: true, data } or { ok: false, problem }, and problem.type ends with a code such as slot-taken, notice-period, invalid-request, not-found, internal-error or network-error.
Facts for messages: clinic phone 01632 960 123, open Monday to Friday, 8:00 to 18:00. Patients may change or cancel online only if the appointment starts at least 24 hours away. The server enforces this and sends the wording.
Tasks:
1. Write a table of messages for every state and problem code, in plain words, without codes or stack traces.
2. Write a view component with a switch over the status, covering every case. Errors use role="alert", other messages role="status".
3. Mark any message that could claim something we cannot know, for example after a timeout.
4. List assumptions. Do not invent rules, numbers or phone details.Show the reusable template
Replace each {{placeholder}} with your own details.
You are helping me handle the states of one screen. Do not add features, libraries or styling.
Project: {{project_and_stack}}.
Screen {{screen_id}}: {{screen_purpose}}, in a {{component_kind}}.
States: {{state_list}}.
Existing types: {{existing_types}}. The API client returns {{result_shape}}, and problem codes are {{problem_codes}}.
Facts for messages: {{facts_for_messages}}
Tasks:
1. Write a table of messages for every state and problem code, in plain words, without codes or stack traces.
2. Write a view component with a switch over the status, covering every case. Errors use role="alert", other messages role="status".
3. Mark any message that could claim something we cannot know, for example after a timeout.
4. List assumptions. Do not invent rules, numbers or phone details.Expected output and limitations
A message table that covers every state and problem code, a view component with a complete switch, a list of messages marked as risky, and a list of assumptions.
Messages
loading -> "Loading free times"
empty -> "No free times on this date. Try another date, or phone the clinic on 01632 960 123."
conflict -> "That time has just been taken. Please choose another time from the list."
network-error -> "We could not reach the booking system. Check your connection and try again."
RISK: after a booking or cancel this may be untrue. Add "look at My bookings first".
View component
switch (state.status) {
case "loading": ...
case "empty": ...
case "error": ...
case "ready": ...
}
Assumptions
- The notice-period message is shown exactly as the server sends it.Limitations to keep in mind
- The assistant may promise things it cannot know, such as 'nothing was changed' after a timeout. Read each message for what it claims.
- It may invent phone numbers, hours or rules. Check every fact against the client's decisions.
- It may skip a state, or make the switch fall through to a blank result. Render every state to be sure.
Common errors and how to fix them
A screen shows a blank page while data loads or after a failure.
Why it happens: Only the ready state was written.
Fix: Add loading, empty and error cases, and use a union type so a missing case is reported.
The error message shows 'Failed to fetch' or a status code.
Why it happens: The raw error was passed straight to the screen.
Fix: Turn each problem into plain words in one component, and keep codes out of what people read.
A message says 'nothing was changed' after a timeout.
Why it happens: The writer assumed the request never arrived.
Fix: Say the result is unknown and tell the person where to check, for example My bookings.
Validation checklist
Tick each item once you have confirmed it.
Hands-on exercise
States for Ferngate's parts list
Ferngate Cycle Repairs has a screen that lists parts taken for a job. Define the state union, write a message for every state, and render each one. Include a state for a lost connection that the mechanic can understand with greasy hands and little time.
You will need
- The screen: 'Parts taken for this job', loaded from the API.
- Note: a new job has no parts yet.
- Note: the workshop connection is unreliable, and mechanics share one tablet.
- Note: the low-stock threshold is still 'to be agreed'.
Acceptance criteria
Your work is done when every one of these is true.
Hints (2)
- A new job is a normal case. Make the empty message welcoming.
- Short messages and large text suit a shared tablet.
Show a model answer
A strong answer has a LoadState union and a view with a complete switch. The empty message says something like 'No parts recorded for this job yet. Use Add part to record the first one.' The lost-connection message says the list could not be loaded, and, for a save, that the entry may not have been recorded, so the mechanic should check the list before adding it again. The low-stock rule does not appear, because it needs an owner's decision. The four rendered outputs prove no state is blank, and the roles are alert for the error and status for the others.
Knowledge check
Choose an answer, then check it. Nothing is recorded — this is for you.
Show the answer and explanation
Answer: B. A union says a value is exactly one of the listed shapes, so half-set mixes cannot be written, and a switch that forgets a case is flagged. It does not change speed, which is a common mix-up, and it does not replace messages: you still have to write them.
Show the answer and explanation
Answer: B. It says what is true and what to do next. 'No data' is tempting because it is short, but it is jargon and gives no direction. A silent empty list reads as broken.
Show the answer and explanation
Answer: C. After a timeout the server may or may not have acted. The honest message says the result is unknown and points to where the truth is. 'Nothing has been changed' sounds comforting but may be false, which could lead to a double cancel or a missed appointment.
Frequently asked questions
What is an empty state in UI design?
It is what a screen shows when the request worked but there is nothing to display, such as a list with no items. A good one explains why it is empty and what the person can do next. A blank area makes people think the page is broken.
How do I show a loading state in React?
Keep the status in state, such as { status: "loading" }, and draw a message or placeholder while it is set. Switch to ready, empty or error when the reply arrives. Keep the text meaningful so a screen reader announces it too.
What should an error message say?
It should say what happened, whether anything is at risk and what the person can do next, in plain words. Avoid codes, stack traces and blame. If you cannot be sure of the result, say so.
Should I use a spinner or a skeleton for loading?
Either can work, and the choice is a design detail. What matters is that the person is told something is loading, and that the text is available to screen readers. Start with a plain message and add a visual later if it helps.
- Written by
- PromptFable Editorial
- Last updated 19 Nov 2026
- Review
- Reviewed by Waseem Nadir, Technical Reviewer
- Last reviewed 27 Nov 2026
References
Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.
- Synchronizing with Effects(opens in a new tab)
React · Official documentation · Explains useEffect, cleanup and why a stale reply must be ignored.
- ARIA live regions(opens in a new tab)
MDN Web Docs · Official documentation · Background on how status and alert messages are announced.
- Error Handling Cheat Sheet(opens in a new tab)
OWASP · Official documentation · Why messages should not expose internal details.
PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.