Sub topic 11
Modeling states in code
This chapter assumes you know TypeScript basics (union types, switch, generics) and how a client fetches data asynchronously. It also assumes you have read the earlier chapters on loading, empty, and error states. Here you will turn those design decisions into types, so the compiler rejects screens that contradict the design.
Why boolean flags break down
Most first implementations track state with independent fields:
type FlagState = {
isLoading: boolean;
error: string | null;
data: string[] | null;
};These three fields allow many combinations, and most of them are meaningless:
isLoading: truewith anerrorset. Does the screen show a spinner or an error?isLoading: false,error: null,data: null. The request finished, yet there is nothing to show.data: []is never given its own treatment, so the screen renders a blank list.
Each combination is a bug the designer never specified. A developer must remember to check the flags in the right order, and a later change can silently break that order. The design says a screen is in exactly one state at a time. The type should say the same.
A discriminated union gives one state at a time
A discriminated union is a union type in which every member carries a literal field, here status, that tells the members apart. TypeScript uses that field to narrow the type inside a switch. Within case "error", the compiler knows message exists and items does not.
The design chapters named more states than loading, error, and success, so the type lists all of them:
type NonEmpty<T> = [T, ...T[]];
type EmptyReason = "first-use" | "no-results";
type ListState<T> =
| { status: "loading" }
| { status: "error"; message: string; retryable: boolean }
| { status: "empty"; reason: EmptyReason }
| { status: "success"; items: NonEmpty<T> }
| { status: "refreshing"; items: NonEmpty<T> }
| { status: "stale"; items: NonEmpty<T>; message: string };
function isNonEmpty<T>(items: T[]): items is NonEmpty<T> {
return items.length > 0;
}
function fromResult<T>(items: T[], query: string): ListState<T> {
if (isNonEmpty(items)) {
return { status: "success", items };
}
return {
status: "empty",
reason: query.trim() === "" ? "first-use" : "no-results",
};
}Four decisions in this code matter.
- Empty is not success with an empty array. The
successmember requires aNonEmptytuple, so a successful state with zero items cannot be built. The only way to represent zero items is theemptymember, which forces you to say why. EmptyReasoncarries the cause. The earlier chapter on empty states separated "nothing created yet" from "your search matched nothing". Those need different messages and different calls to action. Keeping the reason in the state means the view cannot forget the distinction.- One function decides between
successandempty.fromResultis the only place that makes this judgment, so every screen using it applies the same rule. refreshingandstalekeep the old items. A refetch should not blank a screen that already has content.refreshingshows the existing items with a subtle progress cue.stalemeans the refresh failed, so the screen keeps the old items and adds a notice. This is the partial-failure pattern from the recovery chapter, written as a type.
Render every state, and let the compiler check you did
A switch over status is the rendering contract. Add a helper that fails to compile when a case is missing:
function assertNever(value: never): never {
throw new Error(`Unhandled state: ${JSON.stringify(value)}`);
}
function render(state: ListState<string>): string {
switch (state.status) {
case "loading":
return "Loading projects…";
case "error":
return state.retryable
? `${state.message} Try again.`
: state.message;
case "empty":
return state.reason === "first-use"
? "No projects yet. Create your first project."
: "No projects match your search. Clear the search to see all projects.";
case "success":
return state.items.join(", ");
case "refreshing":
return `${state.items.join(", ")} (updating…)`;
case "stale":
return `${state.items.join(", ")} (${state.message} Showing saved data.)`;
default:
return assertNever(state);
}
}After all six cases are handled, state has the type never in the default branch, so assertNever(state) compiles. If someone adds a seventh status to ListState and forgets the view, state is no longer never there and the build fails. That failure is the point: a new state cannot ship without a design for how it looks.
The strings here are plain text so the example runs anywhere. In a real UI each branch returns a component, and each should follow the accessibility rules from the previous chapter. The loading branch renders a polite status region, the error branch uses role="alert", and the empty branch moves focus only when the user's action caused the change.
Make transitions explicit with a reducer
A type describes which states exist. A reducer describes how one state becomes another. Writing transitions as a pure function keeps the timing logic out of components and makes it testable without a browser:
type Action<T> =
| { type: "fetch" }
| { type: "resolve"; items: T[]; query: string }
| { type: "reject"; message: string; retryable: boolean };
function reduce<T>(state: ListState<T>, action: Action<T>): ListState<T> {
switch (action.type) {
case "fetch":
if (state.status === "success" || state.status === "stale") {
return { status: "refreshing", items: state.items };
}
if (state.status === "refreshing") {
return state;
}
return { status: "loading" };
case "resolve":
return fromResult(action.items, action.query);
case "reject":
if (state.status === "refreshing") {
return { status: "stale", items: state.items, message: action.message };
}
return {
status: "error",
message: action.message,
retryable: action.retryable,
};
}
}
let state: ListState<string> = { status: "loading" };
state = reduce(state, { type: "resolve", items: ["Alpha", "Beta"], query: "" });
state = reduce(state, { type: "fetch" });
state = reduce(state, {
type: "reject",
message: "Couldn't refresh.",
retryable: true,
});
console.log(state.status); // "stale"Two details are easy to miss:
- A
fetchwhile alreadyrefreshingreturns the same state object. A double-clicked refresh button therefore does not restart the cycle or flicker. - A
rejectproduces a different state depending on where it arrives. The same network failure becomeserroron a first load andstaleon a refresh. The user needs a full error screen in one case and a small notice in the other.
Treat this diagram as the specification. Every arrow is a case in the reducer. Every state with no arrow into it, such as stale straight from loading, is a transition the code should make impossible.
Where the delay from earlier chapters fits
The timing chapter recommended delaying a spinner so fast responses do not flash it. That delay belongs in the view layer, not in the state. The state is loading the moment the request starts. The view decides whether to paint it yet:
function showAfterDelay(delayMs: number, show: () => void): () => void {
const id = setTimeout(show, delayMs);
return () => clearTimeout(id);
}
// Show the spinner only if the request takes longer than 300 ms.
const cancel = showAfterDelay(300, () => console.log("show spinner"));
// When the request finishes quickly, cancel() prevents a flash of spinner.
cancel();Keeping this separate means tests of the state logic never wait on timers, and you can change the delay without touching the reducer.
Edge cases that the model must handle
- Out-of-order responses. If the user types a second search while the first is in flight, the first response can arrive last and overwrite the newer result. Tag each request with an id or query, and ignore
resolveactions that do not match the latest one. Alternatively, cancel the old request with anAbortController. - Cancellation is not failure. An aborted request should not dispatch
reject. Showing "Something went wrong" because the user navigated away is a false error. - Empty after a refresh. The diagram allows
refreshingtoempty. This happens when another person deleted every item. The screen should switch to the empty state, because showing stale items would be wrong. - Errors that are not retryable. The
retryableflag onerrorlets the view hide the retry button for a permission failure, where trying again cannot help. Set it from the error's cause, as the error taxonomy chapter described. Do not set it from a guess. - Several data sources on one screen. Give each independent region its own
ListState. A single screen-wide status hides partial failure, so one failed widget turns a mostly working dashboard into an error page.
Common modeling mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Separate `isLoading`, `error`, and `data` fields | Spinner and error show together | Use one `status` discriminant |
| Treating `[]` as success | Blank list with no guidance | Make `empty` its own state with a reason |
| Dropping old data on refetch | Content flashes away on every refresh | Add `refreshing` and `stale` states that keep items |
| `default` branch that returns `null` | New states silently render nothing | End with `assertNever` |
| Setting state from inside the view's timers | Race conditions and untestable timing | Keep timers in the view, transitions in the reducer |
| One status for the whole page | One failed panel hides working ones | Model each independent data source separately |
Putting it into practice
- List every state in your design review, including the ones that only exist during a refresh.
- Write the union before writing any component.
- Write the reducer and unit-test each arrow in the state diagram.
- Write the view as an exhaustive
switch. - Add the delay and live-region behavior in the view, using the earlier chapters as the guide.
Following this order means the design decisions from the earlier chapters become compile-time facts instead of conventions someone has to remember.
Exercise
A product manager asks for a new state, "offline", shown when the device has no connection. Describe which parts of the code in this chapter must change, and what the compiler does to help you.
Show answer
Add { status: "offline" } (optionally carrying the last known items) to the ListState union. The render function then fails to compile, because the default branch no longer receives never. That error points you to the view, where you add a case "offline". In reduce, add transitions into and out of offline, for example a reject with a network cause becoming offline, and a retry or "back online" action returning to refreshing or loading. Update the state diagram so the new arrows match the reducer.
Exercise
The type { status: "success"; items: NonEmpty<T> } forbids an empty success. A teammate says this is unnecessary because the view can check items.length === 0. Give two reasons the type-level approach is safer.
Show answer
First, a length check is a runtime convention that each view must remember, and any view that forgets it renders a blank list. The type makes the mistake impossible to construct. Second, the empty state carries a reason, so the user gets different guidance for a first-use screen and a search with no results. A length check on success has nowhere to store that cause. The type also forces fromResult to be the single place that decides which state a response becomes.