Fetching and Typing API Data in React
Model fetch loading and error states, validate unknown JSON at runtime, and cancel outdated requests before rendering typed React results.
Fetch responses cross a runtime boundary, so keep parsed JSON as `unknown` until a guard validates each field the UI uses. A discriminated union makes loading, error, and success branches explicit. This post shows HTTP status checks, effect cleanup with AbortController, and safe rendering of results, with practical guidance for failures and stale responses.
Fetching and Typing API Data in React
Introduction
API responses are outside your control. TypeScript interfaces do not check server data at runtime, so treat parsed JSON as unknown until validation succeeds.
This post follows a request through loading, cancellation, runtime validation, and rendering a typed result.
Describe and validate the response
Describe only fields the UI uses, then check them before treating decoded JSON as a user list:
interface User {
id: string;
name: string;
}
export function isUserList(value: unknown): value is User[] {
return (
Array.isArray(value) &&
value.every(
(item: unknown) =>
typeof item === "object" &&
item !== null &&
"id" in item &&
typeof item.id === "string" &&
"name" in item &&
typeof item.name === "string",
)
);
}
This guard rejects malformed records before they enter success state. An empty array is still valid data, but the UI should show a no-results message instead of a blank list. For larger or frequently changing API shapes, a schema validator can be easier to maintain than handwritten checks.
Fetch with loading, error, and cancellation
This component loads users for the selected team and cancels the request on unmount or when teamId changes. A union keeps loading, failure, and success distinct.
import { useEffect, useState } from "react";
type UserState =
| { teamId: string; status: "loading" }
| { teamId: string; status: "error"; message: string }
| { teamId: string; status: "success"; users: User[] };
export function UserList({ teamId }: { teamId: string }) {
const [state, setState] = useState<UserState>({ teamId, status: "loading" });
useEffect(() => {
const controller = new AbortController();
async function loadUsers() {
setState({ teamId, status: "loading" });
try {
const response = await fetch(
`/api/users?teamId=${encodeURIComponent(teamId)}`,
{ signal: controller.signal },
);
if (!response.ok) throw new Error(`Request failed: ${response.status}`);
const payload: unknown = await response.json();
if (!isUserList(payload)) throw new Error("Unexpected user data");
setState({ teamId, status: "success", users: payload });
} catch {
if (controller.signal.aborted) return;
setState({
teamId,
status: "error",
message: "Could not load users. Try again.",
});
}
}
void loadUsers();
return () => controller.abort();
}, [teamId]);
if (state.teamId !== teamId || state.status === "loading") {
return <p role="status">Loading users…</p>;
}
if (state.status === "error") return <p role="alert">{state.message}</p>;
if (state.users.length === 0) return <p>No users found.</p>;
return (
<ul>
{state.users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
response.json() does not prove the payload matches the interface. Validation narrows it before storing success; the union exposes users only in that branch.
Each state records the teamId that produced it. If the prop changes, the render shows loading until the stored result belongs to the selected team; this hides old users before the new effect runs. The effect then aborts the previous request and loads the new team. A controlled search field can follow the same pattern; see controlled inputs and forms. Start button-triggered searches in the event handler.
Aborting fetch can stop client-side request or response-body work, but it cannot tell you whether a server already processed a mutation. Treat a canceled write as having an unknown outcome and use the endpoint’s idempotency or status-checking mechanism; React’s effect guidance makes the same point about requests that have already happened.
Test the boundary and cleanup
The guard and component snippets above are assumed to be exported from user-list.tsx; the tests below live in user-list.test.tsx. These illustrative tests use Vitest and React Testing Library. Adapt the setup if your project uses a different runner.
import { expect, it } from "vitest";
import { isUserList } from "./user-list";
it("rejects a payload with invalid field types", () => {
const payload: unknown = [{ id: 17, name: null }];
expect(isUserList(payload)).toBe(false);
});
The second test changes teams while the first request is pending. Its mock rejects when the signal is aborted, as fetch does, and the component should stay in its loading state instead of showing an error for an obsolete request.
import { render, screen } from "@testing-library/react";
import { expect, it, vi } from "vitest";
import { UserList } from "./user-list";
it("ignores an aborted request when the team changes", async () => {
const signals: AbortSignal[] = [];
vi.stubGlobal(
"fetch",
vi.fn(
(_input: RequestInfo | URL, init?: RequestInit) =>
new Promise<Response>((_resolve, reject) => {
const signal = init?.signal as AbortSignal;
signals.push(signal);
signal.addEventListener(
"abort",
() => reject(new DOMException("Aborted", "AbortError")),
{ once: true },
);
}),
),
);
try {
const { rerender } = render(<UserList teamId="red" />);
rerender(<UserList teamId="blue" />);
expect(signals[0]?.aborted).toBe(true);
expect((await screen.findByRole("status")).textContent).toBe(
"Loading users…",
);
expect(screen.queryByRole("alert")).toBeNull();
} finally {
vi.unstubAllGlobals();
}
});
Request flow
flowchart TD
A[Start request] --> B{HTTP success?}
B -->|No| C[Show error]
B -->|Yes| D[Parse as unknown]
D --> E{Runtime validation passes?}
E -->|No| C
E -->|Yes| F[Render typed results]
A --> G[Abort on unmount or change]
Trade-Off Table
| Approach | Useful when | Cost |
|---|---|---|
| Type assertion | Rarely, data was validated elsewhere | Does not check the payload |
| Handwritten type guard | Small stable response shape | Must update when the API changes |
| Schema validator | Nested or changing payloads | Adds setup or a dependency |
| Abortable effect | Data follows component or prop lifecycle | Requires cleanup and dependencies |
Production Failure Scenarios
Suppose a deployment changes { id: "17", name: "Mina" } to { id: 17, name: null }. An unchecked cast hides the mismatch; validation catches it and shows an error. A second failure occurs when an earlier search response arrives after a newer one and replaces the results. Abort the old request or check the active request before committing state. Log the route and status, not private payloads.
Common Pitfalls / Anti-Patterns
Check response.ok; fetch resolves even for 404 or 500 responses. Avoid skipping validation or omitting dependencies.
Observability Checklist
- Track duration, HTTP failures, validation failures, and cancellations separately.
- Record a safe request or entity ID, never private payload fields.
- Verify stale or aborted responses do not update the screen.
Security and Compliance Notes
API content is untrusted. Render strings as JSX text, validate URLs before using them as links, and keep credentials out of client code. Types do not sanitize content.
When to Use / When NOT to Use
Fetch when a screen needs server-owned data, then validate JSON before treating it as a TypeScript shape. Use an event handler for a user-triggered search and an effect for data tied to component inputs. Avoid fetching during render or treating a type assertion as runtime validation.
Quick Recap Checklist
- Model loading, error, and success as distinct states.
- Treat parsed JSON as
unknownuntil it passes runtime checks. - Use an abort signal and effect cleanup for lifecycle requests.
- Add changing request inputs to dependencies.
- Render only validated data and keep sensitive values out of logs.
Interview Questions
Parsed JSON can have missing fields or unexpected types. `unknown` requires a runtime check before the application treats it as a specific interface.
No. Check response.ok to handle unsuccessful status codes.
Pass an AbortSignal and abort it in cleanup. A dependency change then cancels the old request before the next starts.
It parses JSON but does not prove the shape matches an application interface.
- Keep the parsed value as
unknown. - Validate its fields before using it as a User.
It should verify every field the component relies on.
- Check both the container and nested values.
- Update the guard when the API contract changes.
Use it when work belongs to a component lifecycle or should be canceled after input changes.
- Pass the signal to
fetch. - Abort during cleanup and ignore cancellation as an ordinary failure.
The effect must request data for the current value.
- Include it in both the URL and dependency list.
- Cleanup cancels the request for the previous value.
Not for an HTTP status alone; the promise resolves with a Response.
- Check
response.okand handle the error state. - Network failures and aborts are separate promise rejection cases.
It keeps the data valid for each request phase together.
- Success can carry users while error carries a message.
- Render branches narrow to the fields that state provides.
Record useful context without copying private response content.
- Include a safe request or entity ID and endpoint.
- Avoid secrets and full payloads in browser logs.
Further Reading
- For the request UI around typed data, read loading and error states.
- For effect cleanup and dependencies, see React effects with useEffect.
- If the request follows a search field, see controlled inputs and forms.
- Learn safe boundary types in nullable and unknown data in TypeScript.
- Union types and narrowing explains the tagged state model.
- Verify user-facing async behavior with component and interaction testing.
- MDN’s guides cover Using Fetch and the AbortController API; TypeScript’s Handbook explains narrowing.
Conclusion
Validate network data at runtime, model fetch states clearly, cancel outdated requests, and render checked values instead of asserting JSON is correct.
Category
Tags
Related Posts
Accessible React UI: Semantics, Labels, and Keyboard Use
Build React interfaces with semantic controls, connected labels, visible keyboard focus, and status announcements through practical TypeScript examples.
Advanced React State: When Local State Stops Fitting
Learn when React state needs a reducer and context, when Redux Toolkit helps, and why server data often belongs in a query cache instead.
Testing React Components and User Interactions
Write behavior-first React tests with accessible roles, realistic user events, and async assertions while avoiding brittle checks of implementation details.