Sub topic 2
Why hand-written loading and error state breaks down
This chapter assumes you know TypeScript with async/await and Promises, Angular components and templates, and the basics of signals (signal, computed, effect). It also assumes you have used fetch or HttpClient before. It does not introduce the resource API yet. Its job is to show the problems that API was designed to remove, so that the design makes sense when you meet it in the next chapter.
The usual pattern
Most Angular developers have written some version of this. A component needs data from a server, so it keeps three pieces of state next to each other: the data, a loading flag, and an error.
import { Component, signal } from '@angular/core';
interface User {
id: number;
name: string;
}
@Component({
selector: 'app-user-manual',
template: `
<button (click)="select(1)">User 1</button>
<button (click)="select(2)">User 2</button>
<button (click)="select(3)">User 3</button>
@if (loading()) {
<p>Loading...</p>
}
@if (error()) {
<p>{{ error() }}</p>
}
@if (user(); as u) {
<p>{{ u.name }}</p>
}
`,
})
export class UserManualComponent {
readonly userId = signal(1);
readonly user = signal<User | undefined>(undefined);
readonly loading = signal(false);
readonly error = signal<string | undefined>(undefined);
constructor() {
this.load(this.userId());
}
select(id: number) {
this.userId.set(id);
this.load(id);
}
private async load(id: number) {
this.loading.set(true);
this.error.set(undefined);
try {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
this.user.set((await res.json()) as User);
} catch (e) {
this.error.set(e instanceof Error ? e.message : 'Unknown error');
} finally {
this.loading.set(false);
}
}
}For one request that runs once, this works. The problems appear when the input changes, when requests overlap, or when the component grows. The rest of the chapter goes through them.
Problem 1: responses arrive out of order
Network responses do not return in the order you sent the requests. Suppose the user clicks "User 2" and then quickly "User 3". Two calls to load are now in flight. If the request for user 2 is slow and the request for user 3 is fast, the responses arrive in the wrong order.
The diagram follows.
The screen now shows user 2 while userId() says 3. No error is thrown, and nothing looks wrong in the code. This is a race condition, and it is hard to reproduce on a fast local network, so it often reaches production.
The loading flag has the same flaw. When the first request finishes, its finally block sets loading to false while the second request is still running. The spinner disappears too early.
Problem 2: fixing it by hand adds more state
The standard fix is to ignore any response that is not from the latest request. One way is a request counter:
private latest = 0;
private async load(id: number) {
const requestId = ++this.latest;
this.loading.set(true);
this.error.set(undefined);
try {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = (await res.json()) as User;
if (requestId !== this.latest) return;
this.user.set(data);
} catch (e) {
if (requestId !== this.latest) return;
this.error.set(e instanceof Error ? e.message : 'Unknown error');
} finally {
if (requestId === this.latest) this.loading.set(false);
}
}This is now correct for the race, but look at what it cost. Every branch needs its own staleness check, and forgetting one reintroduces the bug. The counter is a fourth piece of state that the template never uses. Each component that loads data has to repeat this logic, and each copy can be wrong in a slightly different way.
The counter also does not cancel anything. The superseded request still runs to completion, uses bandwidth, and loads the server. Real cancellation needs an AbortController, which means one more field, one more abort() call before each new request, and a check that treats an AbortError as expected and not as a failure. With HttpClient you would instead keep a Subscription and unsubscribe from it, or use switchMap, which is the same idea in RxJS.
Problem 3: separate flags can contradict each other
The component stores user, loading, and error as three independent signals. Nothing prevents them from holding a combination that makes no sense. The template above shows both the old user and an error message if a reload fails, because user is never cleared. It may also show "Loading..." next to a user from the previous selection.
Is that second case a bug? It depends on what you want. Some interfaces should keep the old data visible while refreshing. Others should blank the screen. The hand-written version does not make that choice explicit. It falls out of whichever set calls you remembered to write.
Count the combinations: three independent values give you many states, but only a few are meaningful.
| State | `user` | `loading` | `error` | Meaningful? |
|---|---|---|---|---|
| Not started | undefined | false | undefined | Yes |
| First load | undefined | true | undefined | Yes |
| Loaded | set | false | undefined | Yes |
| Failed | undefined | false | set | Yes |
| Reloading with old data | set | true | undefined | Yes, if you intend it |
| Failed after earlier success | set | false | set | Only if you intend it |
| Loading and failed together | any | true | set | No |
The last row can happen after a bug. The type system cannot rule it out, because three independent signals can hold any combination.
Problem 4: nobody tests the unhappy paths
The transitions between these states are where bugs live, and they are the part that gets tested least. A typical test checks that data appears after a successful load. It rarely checks that a second failing request clears the spinner, that an error from request 1 is cleared when request 2 succeeds, or that a late response is discarded.
Each missing check corresponds to a real bug that we have already seen in this chapter. Because the logic is spread across try, catch, finally, and the early returns, it is also easy to change one branch and forget another.
Problem 5: the logic does not compose
Now suppose a second request depends on the first. After loading a user, you want to load that user's posts. In the manual version you add three more signals (posts, postsLoading, postsError), a second counter, and a call to the second loader at the end of the first, in the right place and only on success.
Then consider what should happen when the user changes while the posts are still loading, or when the user fails to load and the old posts are still on screen. Each rule is more manual code. The load order is spread across method calls instead of declared in one place.
The same issue appears when you derive state. A computed signal can read user(), but it cannot say whether user() is trustworthy yet, because the loading and error flags are separate signals the computed must also remember to read.
What the problems have in common
The five problems have one cause. The code describes how to run a request, step by step, instead of describing what the data depends on. You write the imperative sequence (set flag, call, set data, clear flag), and every guarantee you want has to be restated at each step.
Signals already solve this problem for synchronous values. A computed does not need a counter or a manual refresh call. It declares what it depends on, and Angular re-evaluates it. Asynchronous reads need the same treatment, with these properties:
- One object holds the value, the status, and the error, so they cannot disagree.
- The request starts again when its input signals change, with no manual
loadcall. - A new request supersedes the old one, and the old one is cancelled.
- A response from a superseded request is never applied.
The resource API, which the next chapters cover, provides these properties.
A checklist for judging your own loading code
When you review a component that loads data by hand, ask these questions. Each "no" is a place where the code can break.
- If the input changes twice quickly, can an older response overwrite a newer one?
- Does the loading flag stay true until the latest request finishes, not the first one?
- Is the old request cancelled, or only ignored?
- Is the previous error cleared when a new request starts or succeeds?
- Is it clear whether old data stays visible during a reload?
- Does a test cover a failing request, and a failing request that follows a successful one?
Exercise
In the manual component, the user clicks "User 2" and then "User 3". The response for user 3 arrives first, then the response for user 2. Name two separate things that go wrong on screen, and say what a request counter fixes and what it leaves unfixed.
Show answer
First, the screen shows user 2 although userId() is 3, because the late response overwrites the newer data. Second, the loading flag is set to false when the first request finishes, so the spinner can disappear while the second request is still running. A request counter makes the component ignore responses and flag resets from superseded requests, which fixes both. It does not cancel the superseded request, so that request still uses the network and the server until it completes. Cancelling needs an AbortController or an unsubscribe.
Exercise
The component stores user, loading, and error as three separate signals. Give one combination of values that the type system allows but that should never be shown, and explain why separate signals cannot prevent it.
Show answer
For example, loading is true while error holds a message from an earlier failed request, so the screen shows a spinner and an old error together. The three signals are independent, so each can be set without checking the others, and TypeScript only checks that each value has the right type. Nothing ties the three together, which is why a single object that holds value, status, and error is safer.