# Add Request Cancellation to a TanStack Query App

Yes. An agent passes TanStack Query's abort signal into your fetch layer, stops the client toasting a cancelled request as an error, tests both, opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-request-cancellation/tanstack-query/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads the fetch layer before any hook, because cancellation only works if the request actually consumes the signal. In an app laid out like alan2207/bulletproof-react (`apps/react-vite`, `@tanstack/react-query` 5.32.1, `axios` 1.6.8), `src/lib/api-client.ts` is an Axios instance whose response interceptor unwraps `response.data` and, on error, pushes a notification with `error.response?.data?.message || error.message` through the `useNotifications` store and redirects on a 401. `src/lib/react-query.ts` sets `retry: false` and `staleTime` of a minute for every query. Each feature's `api/` file builds a `queryOptions` object: `get-discussions.ts` declares `queryFn: () => getDiscussions(page)`, `get-discussion.ts` and `get-teams.ts` do the same, and `get-users.ts` passes `getUsers` itself as the `queryFn`, which receives the query context as its first argument and ignores it. Not one `queryFn` reads the `signal` the context provides, and a search of `src/` for `signal` or `AbortSignal` finds nothing.

So today a query that loses its component keeps running. `discussions-list.tsx` reads `?page=` from `useSearchParams`, and the route's `clientLoader` in `routes/app/discussions/discussions.tsx` fetches each page through `queryClient.fetchQuery`; a user who clicks page 2 and then page 3 before the first answer arrives leaves page 2's request in flight, and the mock server's `networkDelay()` of 300 to 1000 ms makes that easy to do. The change is one argument per fetch: every `queryFn` becomes `({ signal }) => getDiscussions(page, { signal })` and the `api.get` calls pass `{ params, signal }` through, which is all TanStack Query needs to abort the request when the last observer of that query unsubscribes. `get-comments.ts`, the infinite query, gets the same treatment with `pageParam`.

The interceptor is where this goes wrong if left alone. Axios rejects an aborted request with a `CanceledError` whose `response` is empty, so the existing interceptor would read `error.message`, `canceled`, and show it as an error toast on every cancellation. The agent adds an `axios.isCancel(error)` check before the notification and the 401 branch, rejecting silently, and nothing else in the interceptor changes. It also reads the two prefetches, `prefetchQuery(getDiscussionQueryOptions(id))` on hover in the list and `prefetchInfiniteQuery` for comments in the route, and checks against the mock server what happens to them now that their `queryFn` consumes the signal, stating in the pull request whether they ran to completion or aborted on unhover rather than assuming either.

Tests run where the repository runs them. `vite.config.ts` configures Vitest with `jsdom` and the MSW handlers, so the agent writes a test that renders `DiscussionsList`, unmounts it inside the handler's delay, and asserts the notifications store received nothing and the handler saw `request.signal.aborted`, and a second that lets the request finish and asserts the rows render. The handler's delay is 200 ms under `import.meta.env.TEST`, which is enough room. It runs `yarn test`, `yarn lint`, which includes the `check-file` naming rules, and `yarn check-types`, the three steps of `all-cli-checks` in `.github/workflows/react-vite-ci.yml`, before opening the pull request.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add request cancellation to the TanStack Query app in apps/react-vite. Read src/lib/api-client.ts, src/lib/react-query.ts, every file under src/features/*/api, the discussions components and routes, src/testing/mocks/handlers/discussions.ts and vite.config.ts first, and confirm no queryFn consumes the signal today. Pass the signal from each queryFn into the Axios call so a query is aborted when its last observer unmounts, including the infinite comments query. Make the response interceptor ignore cancelled requests with axios.isCancel before it shows a notification or handles a 401. Check what happens to the hover prefetches against the mock server and report it. Write Vitest tests that unmount during the mock delay and assert no notification and an aborted request, and one that lets the request finish. Run yarn test, yarn lint and yarn check-types, and open a pull request quoting the test output.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request that changes each `api/` file under `src/features/` by one argument, adds a guard to `src/lib/api-client.ts`, and adds two tests. Its description lists every `queryFn` that now consumes the signal, shows the interceptor diff, states what the hover prefetches did under the mock server, and quotes the Vitest, lint and type-check output.

The run's record keeps the test runs, so a reviewer can see the aborted request asserted in the handler rather than inferred from a missing toast.

Before merging, a reviewer decides whether mutations should get a signal too, which TanStack Query does not abort on unmount and which the pull request leaves alone, and whether `react-query-auth`'s user query in `src/lib/auth.tsx` should pass the signal as well, since it is fetched once at load and rarely loses its observer.

## Run it on every Linear issue labelled performance

An automation in the Project with a `linear` trigger runs this prompt when an issue gets the `performance` label, with the issue's text added after the prompt, so a report of stale responses landing after navigation drives one run and one pull request. The automation runs as the member who last changed it and caps itself with `max_runs_per_hour`.

A team with several React apps on TanStack Query starts one run per repository from a script, `POST /o/{org}/sessions` with this `input` and the repository in `resources`, and a `request_id` that is a UUID v5 of the repository's full name so a retried call returns the run already started. Each run reads that app's own fetch layer, so one on `fetch` instead of Axios gets `{ signal }` on the `fetch` call and a check for `AbortError` in its error handling.

## Why run it on Rush?

The change is one argument in a dozen places and one guard in an interceptor, and the mistake is easy: pass the signal and ship a toast that says `canceled` to every user who navigates quickly. The agent reads the interceptor first, proves the abort in a test that unmounts mid-request, and keeps the output in its run's record.

The same job across many apps runs in parallel, one sandbox each, and every pull request lists that app's own `queryFn` calls and its own test output, so a reviewer checks evidence rather than a pattern.

## Frequently asked questions

### What exactly cancels the request?

TanStack Query passes an `AbortSignal` in the `queryFn` context, and once a `queryFn` reads it, the library aborts that signal when the query's last observer unsubscribes, such as the component unmounting or the page changing. Axios listens on the signal and rejects with a `CanceledError`.

### Why change the interceptor?

Because the existing one treats every rejection as an error worth a toast and reads `error.message` when there is no response, which for a cancelled request is `canceled`. `axios.isCancel` identifies those and the interceptor rejects them silently so the component that already unmounted has nothing to show.

### Does this affect retry or stale data?

No. `retry` is already `false` in `src/lib/react-query.ts`, and a cancelled query keeps whatever data it had and goes back to its previous state; the next observer refetches if the data is stale. Nothing cached is thrown away.

### Do mutations get cancelled too?

No. TanStack Query does not abort mutations when a component unmounts, because a half-sent `POST` is worse than a completed one, and the pull request leaves `create-discussion.ts` and the other mutations without a signal on purpose.

## More TanStack Query jobs

- [Fix "Bad Argument Type. Starting with v5, Only the Object Form Is Allowed" After a TanStack Query Upgrade](https://getrush.ai/run/fix-bad-argument-type-only-object-form-allowed/tanstack-query/)
- [Add Global Error Handling to TanStack Query](https://getrush.ai/run/add-api-error-handling/tanstack-query/)
- [Add Infinite Scroll to a TanStack Query List](https://getrush.ai/run/add-infinite-scroll/tanstack-query/)

## More jobs like this: Turn a Linear label into a PR

- [Add Request ID Logging to a FastAPI App](https://getrush.ai/run/add-request-id-logging/fastapi/)
- [Add Request IDs and Structured Logging to a Gin API from a Linear Issue](https://getrush.ai/run/add-request-id-logging/gin/)
- [Add Request ID Logging to a Rocket App](https://getrush.ai/run/add-request-id-logging/rocket/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
