REACT Contents

API Response Typing Strategies

Type API responses at the boundary and map DTOs into stable view models. Prevent UI coupling to transport shapes and avoid runtime crashes with validation, narrowing, and explicit conversion.

On this page

Boundary Rule

  • Transport data is untrusted. Treat API responses as unknown until validated.
  • DTO types describe transport shape, not business invariants.
  • Map DTO to a stable ViewModel for UI consumption.

DTO vs ViewModel

  • DTO: matches the API contract, can change with backend evolution.
  • ViewModel: stable UI contract, minimal fields required for rendering.
  • Production rule: UI state should store ViewModel, not raw DTO.

Example: DTO and ViewModel

type UserDTO = {
  id: string;
  full_name: string;
  created_at: string; // ISO string
  role: string;
};

type UserVM = {
  id: string;
  name: string;
  createdAtMs: number;
  role: "admin" | "member";
};

Mapping and Validation

function toRole(x: unknown): "admin" | "member" {
  return x === "admin" ? "admin" : "member";
}

function toUserVM(dto: any): UserVM {
  if (!dto || typeof dto !== "object") throw new Error("invalid");
  if (typeof dto.id !== "string") throw new Error("invalid");
  if (typeof dto.full_name !== "string") throw new Error("invalid");
  if (typeof dto.created_at !== "string") throw new Error("invalid");

  const ms = Date.parse(dto.created_at);
  if (!Number.isFinite(ms)) throw new Error("invalid");

  return {
    id: dto.id,
    name: dto.full_name,
    createdAtMs: ms,
    role: toRole(dto.role),
  };
}

Error Normalization

  • Normalize API errors into a consistent UI shape.
  • Split into field errors and a global message.
  • Attach request metadata: endpoint, request id, status code.

Operational Checklist

  • All fetch boundaries validate and map before storing in UI state.
  • UI never depends on raw DTO field names.
  • Parsing failures surface as explicit error state.
  • Transport changes require updating mapping only, not UI components.

Failure Modes

  • UI breaks when backend renames a field and UI reads DTO directly.
  • Unsafe casts allow invalid data and cause runtime crashes later.
  • Date and number parsing errors create NaN and corrupted displays.
  • Inconsistent error shapes cause scattered UI handling and missed retries.

Incident Triage

  • If UI crashes after an API change, inspect DTO mapping first.
  • If data is missing, confirm validation and narrowing logic.
  • If errors look inconsistent, standardize error normalization in the API layer.