What you'll learn: By the end of this lesson you will be able to list the states a screen showing remote data can be in, tell first loading from refreshing, tell an empty result from a failed one, classify errors (network, HTTP, render), decide which errors block a screen and which only warn, announce each state to assistive technology without moving focus, and test every state without a browser.
Think of a restaurant waiter. A good one says "your table will be ready in a few minutes" (loading), "the kitchen is out of that dish" (error) and "we have no vegetarian starters tonight" (empty). A bad one stands silent. Every screen that depends on a server is that waiter: until you design what it says in each situation, it says nothing, or the wrong thing.
The running example is the order history page of a grocery marketplace (the front end of the ShopStream marketplace used in this course): a list of past orders, a search box and a status filter. Fetching orders can be slow, can fail and can legitimately return nothing.
The core idea
- Remote data is never just "the data". At any moment the screen is in one of a few states: nothing yet and loading, data and quiet, data and refreshing, data and a failed refresh, empty, or failed with nothing to show.
- Loading and error can coexist with content. Data you already have is worth keeping while you refresh it or when the refresh fails.
- Empty is a result, not a failure. "No orders yet" and "no orders match this filter" are different messages with different next steps, and neither is an error.
The states
| State | Data on hand? | What is happening | What the user needs |
|---|---|---|---|
| Loading (first) | No | A request is in flight | A sign that something is coming, ideally the shape of the content |
| Content | Yes | Idle | The content |
| Refreshing | Yes | A request is in flight in the background | The content, plus a quiet sign of the refresh |
| Error (blocking) | No | The request failed | What went wrong, and a way to try again |
| Error (refresh failed) | Yes | A refresh failed | The old content, plus a non-blocking notice and a retry |
| Empty | Yes, and it has no items | Idle | Why it is empty, and what to do next |
The two questions "do I have data" and "is a request running" are independent. Server State, Caching and Revalidation describes the cache and its separate status and fetchStatus fields.
Figure 1. Choosing the view
on hand?"} A -->|"no"| B{"Did the last
request fail?"} B -->|"no"| L["Loading placeholder"] B -->|"yes"| E["Blocking error
with Try again"] A -->|"yes"| C{"Is the list
empty?"} C -->|"yes"| M["Empty state
(nothing yet / no matches)"] C -->|"no"| D["Content
+ refreshing indicator if fetching
+ error banner if the refresh failed"]
How to read this: "is there data" comes first, because it decides whether anything can be kept. Everything about requests (running, failed) only changes what is added around the data or, when there is none, what stands in for it.
Where errors come from
An error is not one thing, and the right response depends on where it appeared.
- A network failure (no connection, a DNS failure).
fetch()rejects. MDN says afetch()promise only rejects when the request fails, for example because of a badly formed URL or a network error. - An HTTP error status. The promise does not reject. MDN says it does not reject on statuses such as 404 or 504, and that your code must check
Response.okorResponse.status. - A response you cannot use (invalid JSON, wrong shape). Parsing throws after a successful fetch; treat it as an error too, and see the contracts lessons in this module for validating it.
- A render error. A component throws while rendering. React's error boundaries catch these in their children, but not errors in event handlers, in server rendering, or in asynchronous callbacks such as
setTimeout.
Illustration 1: the minimal example
Two failures that look different in code. Run in Node (the second line needs no network access beyond a local port that refuses the connection):
const missing = new Response("no such product", { status: 404 });
console.log("resolved, ok:", missing.ok, "status:", missing.status);
try {
await fetch("http://127.0.0.1:1/");
} catch (error) {
console.log("rejected:", error instanceof TypeError, error.name);
}
Output, from running it in Node 26.13.1:
resolved, ok: false status: 404
rejected: true TypeError
A Response with a 404 status resolves, with ok false: a try/catch around await fetch() alone would treat it as success. The refused connection rejects (in Node, with a TypeError). A data layer should turn both into one error type before the UI sees them, so a component deals with "failed" and with a message, not with transport details.
Figure 2. Classify once, show once
How to read this: three transport failures converge in the accent box into one error value that the view reads. The error boundary is a separate safety net for a component that throws while rendering; it does not see these asynchronous failures unless you rethrow them into render.
Loading, and keeping what you have
A first load has nothing to show, so a placeholder stands in: a spinner, or better a skeleton with the shape of the content, which helps the layout stay put (see the CLS and layout stability lesson). A refresh is different: keep the data on screen and add a small indicator.
React's own documentation draws the same line. A suspending update normally replaces visible content with the Suspense fallback; wrapping the update in startTransition tells React to keep showing the previous content instead of hiding already revealed content, and useDeferredValue keeps the old results on screen while new ones load, so you can dim them rather than replace them. React also notes that Suspense does not detect data fetched inside an Effect or an event handler, so those sources have to supply their own loading state.
Illustration 2: the realistic example
The view logic above fits in one pure function of four facts: is there data, is it empty, is a request running, did the last one fail. Run in Node:
function viewOf({ data, fetching, error, filtered }) {
if (data === undefined) {
if (error) return "error (blocking), with Try again";
return fetching ? "loading (skeleton)" : "idle";
}
if (data.length === 0) return filtered ? "empty: no matches, offer to clear filters" : "empty: nothing yet, explain what to do";
const notes = [];
if (fetching) notes.push("refreshing indicator");
if (error) notes.push("non-blocking error banner");
return "content" + (notes.length ? " + " + notes.join(" + ") : "");
}
const rows = [
{ data: undefined, fetching: true },
{ data: undefined, fetching: false, error: "HTTP 503" },
{ data: [], fetching: false, filtered: false },
{ data: [], fetching: false, filtered: true },
{ data: ["tea", "coffee"], fetching: false },
{ data: ["tea", "coffee"], fetching: true },
{ data: ["tea", "coffee"], fetching: false, error: "HTTP 503" },
];
for (const r of rows) {
const input = `data=${r.data === undefined ? "none" : r.data.length} fetching=${!!r.fetching} error=${r.error ?? "-"} filtered=${!!r.filtered}`;
console.log(input.padEnd(54), "->", viewOf(r));
}
Running it on seven combinations gives, from Node 26.13.1:
data=none fetching=true error=- filtered=false -> loading (skeleton)
data=none fetching=false error=HTTP 503 filtered=false -> error (blocking), with Try again
data=0 fetching=false error=- filtered=false -> empty: nothing yet, explain what to do
data=0 fetching=false error=- filtered=true -> empty: no matches, offer to clear filters
data=2 fetching=false error=- filtered=false -> content
data=2 fetching=true error=- filtered=false -> content + refreshing indicator
data=2 fetching=false error=HTTP 503 filtered=false -> content + non-blocking error banner
Each row is one rule of the figure. Because it is a pure function, every state can be tested with plain inputs, and a component cannot invent an impossible combination such as "loading and empty at once".
The same two facts appear in the cache model used in the server-state lesson.
Two lines from the captured output of the query-cache lab (examples/frontend/golden/query-cache-model.txt; they are not adjacent in that file, and this lesson ships no new lab):
t= 0s state: status=pending fetchStatus=fetching data=undefined observers=2 invalidated=false entries=1
t= 36s state: status=success fetchStatus=fetching data="v2" observers=3 invalidated=true entries=1
The first line is a first load: status=pending with data=undefined while fetchStatus=fetching. The second is a refetch after an invalidation: status=success with data="v2" still present while fetchStatus=fetching. The data is kept, and "fetching" only adds a refreshing indicator. That model is the lab's own, written to follow the documented rules of a query library; it is not that library.
Empty is a result
An empty list has at least two meanings, and the page should say which.
- Nothing yet: the user has no orders. Explain what the page is for and offer the first action ("Browse the catalogue").
- No matches: orders exist but the search or filter excludes them. Say so, show the active filters and offer to clear them.
Treating either as an error is wrong (nothing is broken), and a blank area says nothing. Do not confuse empty with not arrived yet: until the first response lands there is no data, and "No orders found" would be a lie.
Announcing the states
A sighted user sees a spinner appear and vanish. A screen-reader user needs the same facts in words, without losing their place.
- Loading, refreshing and empty are advisory. MDN's
statusrole is a live region with an implicitaria-liveofpoliteandaria-atomicoftrue, and says not to give it focus. WCAG's guidance on status messages says brief messages such as "Searching..." or "18 results returned" count as status messages when they do not take focus, while the list of results itself is not one. - A blocking error may use
role="alert", which MDN says is equivalent toaria-live="assertive"andaria-atomic="true". MDN also warns that alerts are disruptive and must be used sparingly, and says the element should be in the page before its content changes: a new element already populated with the message generally does not lead to an announcement. aria-busy="true"on a region says it is being updated and that assistive technology may wait before announcing changes; set it back tofalsewhen the update is done.
The lab (below) renders its status and alert elements only while the state applies. Its tests check the roles and the text, not whether a screen reader announces them, and MDN's advice suggests a production version would keep an empty live region mounted. This lesson does not claim any announcement was verified.
Figure 3. A refresh that fails
How to read this: nothing the shopper had is lost when the refresh fails. The retry is a user action; an automatic retry policy is a separate decision with its own limits.
Illustration 3: a failure, from the lab
The feed lab from the pagination lesson has all three states in a list. Its tests (run: 33 passed with Node 26.13.1 and Vitest 5.1.0) assert that: a failed page shows an alert with a "Try again" button, keeps the items already shown and does not retry by itself (no request is made until the button is pressed); that the feed is marked aria-busy while a request is in flight; and that a search with no matches shows a status line "No products found" rather than a blank area or an error. The behaviours were observed through those tests in jsdom only: no output, layout or screen reader was observed.
Trade-offs
| Choice | Gain | Cost |
|---|---|---|
| Skeleton placeholder | Stable layout, clear shape | One more component per screen |
| Keep old data while refreshing | No flicker, nothing lost | The data can be stale: say so if it matters |
| Blocking error for every failure | Simple | A failed refresh hides good data |
role="alert" for errors |
Prompt announcement | Disruptive when overused |
| One error type from the data layer | Views stay simple | A mapping layer to maintain |
Build it
This lesson has no new lab. The best fit is the existing examples/frontend/labs/pagination-infinite-scroll (the states in a list, with a fake server whose answers the test controls). The two small scripts above are plain Node and need no install. The query-cache lines come from the existing query-cache-model golden. No new output is captured here beyond the Node snippets.
cd examples/frontend/labs/pagination-infinite-scroll
../../node_modules/.bin/vitest run
Verified. The 33 tests in the feed lab passed, including the failure, retry, aria-busy and empty-result tests named above. The two Node snippets in this lesson were run and their output is shown unedited. Browser behaviour, screen readers and visual appearance were not tested.
In practice: the order history page
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
The order history page fetches orders on load and when the filter changes. Today it shows a spinner for every request, replaces the list with it, shows "Something went wrong" for every failure, and shows a blank area when there are no orders. Support hears "the page is broken" from new customers with no orders, and from customers whose refresh failed.
Starting architecture
Figure 4. One boolean per concern
How to read this: the warning boxes are where states are tracked as independent flags, which allows impossible combinations and hides the data whenever a request runs or fails.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| Per-screen custom messages | Better wording | Copy for each screen | States still inconsistent |
A shared viewOf state function and components |
One rule for all screens | Refactor of each page | Edge cases the function does not model |
| Rely on a query library's status fields | Less code | A dependency; you still design the messages | Misreading the fields |
The decision
| Field | Decision record |
|---|---|
| Context | Spinners replace lists, every failure looks the same, and empty looks like a bug. |
| Decision | Derive one view state from (data, empty, fetching, error) with a pure function. Keep data while refreshing or when a refresh fails. Separate "nothing yet" from "no matches". Announce loading and empty politely and a blocking error as an alert. |
| Consequences, good | The list never vanishes; support gets clearer reports; each state is testable. |
| Consequences, bad | More states to design, write copy for and test. |
| Revisit when | Retry policy, offline support or optimistic updates change what "failed" means. |
Rollout and verification
- Write the table of states for the page and the copy for each, before coding.
- Test the function for every row, and the page for each state with a fake data layer.
- Force each state by hand: a slow response, a 503, an empty account, a filter with no matches, a failed refresh.
- Check with a keyboard and a screen reader that each state is announced once and focus does not jump.
The 2 a.m. failure
A third-party outage makes the orders API return 503. Customers with cached orders see a full-page error and cannot see their last order, because the page treats any failure as blocking even when it has data.
First three checks: (1) look at the view state when data exists and the refresh failed; (2) check whether the error handling clears the data; (3) see whether the page retries automatically and adds load to the failing service. Mitigation: show the old data with a "could not refresh" banner. Follow-up: a test for the "data plus failed refresh" row.
Architect's notes
- Design the table before the components. Every row needs copy, a visual and a test.
- Derive, don't toggle. One pure function prevents impossible combinations.
- Classify errors where they enter, so the view never sees a status code.
- Keep live regions boring. Polite for status, assertive only when the user must act now.
Common mistakes
- A blank area for empty or for not-yet-loaded.
- Treating HTTP 404 or 503 as success because
fetch()resolved. - A full-page spinner on every refresh.
- One generic message for all errors.
- Retrying automatically with no limit.
- Relying on an error boundary for failed requests. It catches render errors, not asynchronous ones.
- An alert for something that is only advisory.
Key takeaways
- A data screen has a small set of states; derive the view from "data on hand, empty, fetching, failed".
- Keep existing data while refreshing and when a refresh fails.
- Empty is a result with two meanings: nothing yet and no matches.
fetch()rejects on network failure but resolves on an HTTP error; checkok.- Error boundaries catch render errors, not asynchronous request failures.
- Use
statusfor advisory messages andalertsparingly, and never move focus to announce them.
Practice exercises
Exercise 1: Starter (30 min). Predict, then check in Node, what new Response("x", { status: 500 }).ok is, and why a try/catch around await fetch() does not catch it.
Exercise 2: Intermediate (2 hours). Add a "failed and stale" row to viewOf for data older than a limit you choose, with a test per row.
Exercise 3: Advanced (half day). Keep an empty role="status" element mounted in the feed and move the message into it, then explain what you could and could not verify in jsdom.
Related reading
In this course:
- Server State, Caching and Revalidation: the cache that decides whether data is on hand.
- Pagination: Offset, Cursor and Infinite Scroll: the states in a list that loads page by page.
- Optimistic Updates and Rollback: the failure of a write, with the same keep-what-you-have idea.
- CLS and Layout Stability: why placeholders should reserve space.
- Streaming SSR and Suspense: fallbacks while the server streams.
Official documentation
- MDN: Window.fetch(): when the promise rejects and when it resolves.
- React: Suspense: fallbacks, transitions and stale content.
- React: Component (error boundaries): what error boundaries catch and miss.
- MDN: ARIA status role and alert role: polite and assertive announcements.
- WCAG 2.2: Understanding Status Messages: status messages without moving focus.
- MDN: aria-busy: marking a region as being updated.