← React / TypeScript

React / TypeScript · 21 / 24

Server data with TanStack Query and cancellation

Verify cached data and a cancelled HTTP call against a local test server.

  • Large
  • Advanced
  • 90 min

Prerequisites: HTTP contracts and runtime validation, TypeScript: generics and discriminated unions

In this tutorial
  1. Understand the state model
  2. Start the project
  3. Verify the contract with a test
  4. Observe failures and boundaries
  5. Implement the exercise
  6. Verify the solution
  7. Exercise and solution
  8. Project context and sources

Download learning package

Setup and verification

Node.js 22.23 or newer with npm. Python 3 is also required for the common verification entry point. Extract the learning package into a new folder and run python3 run_checks.py there. The script copies the included files into a temporary learning directory. It verifies the example and then the supplied solution there, preserving the original files. Required packages are downloaded on the first run.

Verified on 2026-10-20 on Linux x86_64. A local server counts requests. Re-reading fresh data must not issue another request. The solution invalidates the key and expects another request. A cancelled call must not place a valid record in the cache.

Server data belongs to an addressable query. Its query key separates resources. An AbortSignal only works when the transport consumes it. Tests start a local HTTP server and verify response data and reuse rather than merely mocking a hook.

Package contents and individual files

01Understand the state model

A query key identifies cached data. staleTime describes freshness. The queryFn receives an AbortSignal and passes it to fetch. That connection allows a cancelled query to stop its active transport.

src/App.tsx · typescriptOpen file
import {
  QueryClient,
  QueryClientProvider,
  useQuery,
} from "@tanstack/react-query";
export async function loadVehicles(
  base: string,
  signal: AbortSignal,
): Promise<string[]> {
  const response = await fetch(base + "/vehicles", { signal });
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  const value: unknown = await response.json();
  if (!Array.isArray(value) || !value.every((x) => typeof x === "string"))
    throw new Error("Invalid vehicles");
  return value;
}
const client = new QueryClient({
  defaultOptions: { queries: { retry: false, staleTime: 60000 } },
});
function Vehicles() {
  const query = useQuery({
    queryKey: ["vehicles"],
    queryFn: ({ signal }) => loadVehicles("http://127.0.0.1:4107", signal),
  });
  if (query.isPending) return <p role="status">Loading</p>;
  if (query.isError) return <p role="alert">{query.error.message}</p>;
  return (
    <main>
      <h1>Vehicles</h1>
      <ul>
        {query.data.map((name) => (
          <li key={name}>{name}</li>
        ))}
      </ul>
      <button onClick={() => query.refetch()}>Refresh</button>
    </main>
  );
}
export default function App() {
  return (
    <QueryClientProvider client={client}>
      <Vehicles />
    </QueryClientProvider>
  );
}

02Start the project

Install the pinned dependencies and run npm run dev. Data consists of synthetic learning values. Run node server.mjs in a second terminal. This local learning server supplies the vehicle list.

package.json · jsonOpen file
{
  "name": "appfabrik-learning",
  "private": true,
  "type": "module",
  "scripts": {
    "dev": "vite --host 127.0.0.1",
    "build": "tsc --noEmit && vite build",
    "test": "vitest run src"
  },
  "dependencies": {
    "react": "19.2.3",
    "react-dom": "19.2.3",
    "react-router-dom": "7.18.4",
    "@tanstack/react-query": "5.104.5"
  },
  "devDependencies": {
    "vite": "8.1.5",
    "typescript": "6.0.3",
    "@types/react": "19.2.14",
    "@types/react-dom": "19.2.3",
    "@types/node": "22.19.15",
    "vitest": "4.1.10",
    "@testing-library/react": "16.3.2",
    "@testing-library/user-event": "14.6.1",
    "jsdom": "29.1.1",
    "@playwright/test": "1.64.1"
  }
}

03Verify the contract with a test

A local server counts requests. Re-reading fresh data must not issue another request. The solution invalidates the key and expects another request. A cancelled call must not place a valid record in the cache.

src/App.test.tsx · typescriptOpen file
import { test, expect } from "vitest";
import { createServer } from "node:http";
import { once } from "node:events";
import { QueryClient } from "@tanstack/react-query";
import { loadVehicles } from "./App";
test("real HTTP response is cached and cancellation is propagated", async () => {
  let requests = 0;
  const server = createServer((req, res) => {
    requests++;
    res.setHeader("Content-Type", "application/json");
    res.end('["Family car"]');
  });
  server.listen(0, "127.0.0.1");
  await once(server, "listening");
  const address = server.address();
  if (!address || typeof address === "string") throw Error("No port");
  const base = `http://127.0.0.1:${address.port}`;
  const client = new QueryClient({
    defaultOptions: { queries: { retry: false, staleTime: 60000 } },
  });
  const query = {
    queryKey: ["vehicles"],
    queryFn: ({ signal }: { signal: AbortSignal }) =>
      loadVehicles(base, signal),
  };
  try {
    expect(await client.fetchQuery(query)).toEqual(["Family car"]);
    expect(await client.fetchQuery(query)).toEqual(["Family car"]);
    expect(requests).toBe(1);
    const controller = new AbortController();
    controller.abort();
    await expect(loadVehicles(base, controller.signal)).rejects.toThrow();
    expect(requests).toBe(1);
  } finally {
    client.clear();
    server.closeAllConnections();
    await new Promise<void>((resolve) => server.close(() => resolve()));
  }
});

test("an in-flight request observes cancellation", async () => {
  let arrived!: () => void;
  const seen = new Promise<void>((resolve) => {
    arrived = resolve;
  });
  const server = createServer(() => {
    arrived();
  });
  server.listen(0, "127.0.0.1");
  await once(server, "listening");
  const address = server.address();
  if (!address || typeof address === "string") throw Error("No port");
  const controller = new AbortController();
  const result = loadVehicles(
    `http://127.0.0.1:${address.port}`,
    controller.signal,
  ).then(
    () => "unexpected success",
    (error) => error.name,
  );
  try {
    await seen;
    controller.abort();
    expect(await result).toBe("AbortError");
  } finally {
    controller.abort();
    server.closeAllConnections();
    await new Promise<void>((resolve) => server.close(() => resolve()));
  }
});

Run / check

npm install
npm test
npm run build
Expected result

A local server counts requests. Re-reading fresh data must not issue another request. The solution invalidates the key and expects another request. A cancelled call must not place a valid record in the cache.

04Observe failures and boundaries

Change the expected output and observe a failed test. A TypeScript build protects type contracts while a browser test protects interactions. The two checks serve different purposes.

05Implement the exercise

Invalidate the query key and verify a new HTTP call follows.

06Verify the solution

Invalidation marks the value stale. The next fetchQuery reads again. The solution checks both contents and actual received request count. Copy the solution files to the corresponding locations in the learning project and run tests and build again.

Expected result

Tests and type checking pass. The observed result matches the learning goal.

Your exercise

Invalidate the query key and verify a new HTTP call follows.

Show the solution and explanation

Invalidation marks the value stale. The next fetchQuery reads again. The solution checks both contents and actual received request count.

solution/App.test.tsx · typescriptOpen file
import { test, expect } from "vitest";
import { createServer } from "node:http";
import { once } from "node:events";
import { QueryClient } from "@tanstack/react-query";
import { loadVehicles } from "./App";
test("real HTTP response is cached and cancellation is propagated", async () => {
  let requests = 0;
  const server = createServer((req, res) => {
    requests++;
    res.setHeader("Content-Type", "application/json");
    res.end('["Family car"]');
  });
  server.listen(0, "127.0.0.1");
  await once(server, "listening");
  const address = server.address();
  if (!address || typeof address === "string") throw Error("No port");
  const base = `http://127.0.0.1:${address.port}`;
  const client = new QueryClient({
    defaultOptions: { queries: { retry: false, staleTime: 60000 } },
  });
  const query = {
    queryKey: ["vehicles"],
    queryFn: ({ signal }: { signal: AbortSignal }) =>
      loadVehicles(base, signal),
  };
  try {
    expect(await client.fetchQuery(query)).toEqual(["Family car"]);
    expect(await client.fetchQuery(query)).toEqual(["Family car"]);
    expect(requests).toBe(1);
    const controller = new AbortController();
    controller.abort();
    await expect(loadVehicles(base, controller.signal)).rejects.toThrow();
    expect(requests).toBe(1);
    await client.invalidateQueries({ queryKey: ["vehicles"] });
    await client.fetchQuery(query);
    expect(requests).toBe(2);
  } finally {
    client.clear();
    server.closeAllConnections();
    await new Promise<void>((resolve) => server.close(() => resolve()));
  }
});

test("an in-flight request observes cancellation", async () => {
  let arrived!: () => void;
  const seen = new Promise<void>((resolve) => {
    arrived = resolve;
  });
  const server = createServer(() => {
    arrived();
  });
  server.listen(0, "127.0.0.1");
  await once(server, "listening");
  const address = server.address();
  if (!address || typeof address === "string") throw Error("No port");
  const controller = new AbortController();
  const result = loadVehicles(
    `http://127.0.0.1:${address.port}`,
    controller.signal,
  ).then(
    () => "unexpected success",
    (error) => error.name,
  );
  try {
    await seen;
    controller.abort();
    expect(await result).toBe("AbortError");
  } finally {
    controller.abort();
    server.closeAllConnections();
    await new Promise<void>((resolve) => server.close(() => resolve()));
  }
});

Project context and sources

This independent learning project explores a topic in this technology area. Project references provide a pinned revision as architectural context. They do not imply that every library or feature introduced here is already used in that application.