# Add Infinite Scroll to a TanStack Query List

Yes. The agent swaps a Load more button for an observed sentinel on the existing useInfiniteQuery, fixes the last-page check and tests it under jsdom.

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

## What the agent does

Most of infinite scroll is already there once a list uses `useInfiniteQuery`; what is missing is the trigger. In an app like alan2207/bulletproof-react (`apps/react-vite`, `@tanstack/react-query` 5), comments are loaded by `getInfiniteCommentsQueryOptions` in `src/features/comments/api/get-comments.ts`: the key is `['comments', discussionId]`, `initialPageParam` is 1, and `getNextPageParam` returns the next page number until `meta.page` equals `meta.totalPages`. `comments-list.tsx` flattens `data.pages` and, while `hasNextPage` is true, renders a Load More Comments button that calls `fetchNextPage()`. The agent reads those two files, the route's `clientLoader`, which fetches the first page with `fetchInfiniteQuery` before the page renders, and the mutations that invalidate the same key.

It replaces the button's click with an `IntersectionObserver`. A small element after the last comment is rendered only while `hasNextPage` is true; an effect observes it with a `rootMargin` so the fetch starts before the reader reaches the end, calls `fetchNextPage()` when it intersects and `isFetchingNextPage` is false, and disconnects on cleanup. The button stays inside that element. A keyboard user, or a browser where the observer never fires, still has a control that loads more, and the spinner the button already shows while fetching keeps its place.

Before trusting the observer, the agent checks when the list ends, because a trigger that fires without a click turns an off-by-one into a request loop. The mock API in `src/testing/mocks/handlers/comments.ts` computes `totalPages` as `Math.ceil(total / 10)`, so a discussion with no comments answers page 1 of 0. The comparison `page === totalPages` is then false, `getNextPageParam` returns 2, and `hasNextPage` is true for an empty list. Nothing happens today, because the component returns its empty state before it reaches the button. With a sentinel in the wrong place the same value would ask for page 2, then 3, and never stop. The agent changes the comparison to `>=` and keeps the sentinel out of the empty state.

The test environment needs one addition. Vitest runs these tests in jsdom, where `typeof IntersectionObserver` is `"undefined"`, so a list long enough to render the sentinel would throw. `src/testing/setup-tests.ts` already stubs `ResizeObserver` with `vi.stubGlobal` before each test; the agent adds an `IntersectionObserver` stub beside it that keeps the callback it was constructed with. A new test seeds fifteen comments through the mock database, expects ten list items, calls the stored callback with `isIntersecting: true`, and expects fifteen and no sentinel. A second test covers the empty discussion and asserts that exactly one request was made.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Replace the Load more button on the comments list with infinite scroll. Read the infinite query options and hook for comments, the component that renders the list, the route loader that prefetches it, the mutations that invalidate its query key, the API mock handlers for comments, and the test setup file first. Install dependencies, create .env from .env.example, and record the results of the type check, lint and tests before changing anything. Keep the existing useInfiniteQuery and its query key. Render a sentinel element after the last item only while hasNextPage is true, observe it with IntersectionObserver using a rootMargin, call fetchNextPage only when it intersects and no next page is already being fetched, and disconnect in the effect cleanup. Keep the existing button inside the sentinel as the keyboard and no-observer path. Check getNextPageParam against what the API returns for an empty list and for a list that is an exact multiple of the page size, and fix it if either reports a next page that does not exist. Add an IntersectionObserver stub to the shared test setup next to the existing ResizeObserver stub. Add tests: a list longer than one page loads the second page when the sentinel intersects and then removes the sentinel; an empty list makes exactly one request. Do not add a scroll library or a virtualised list. Open a pull request with the type check, lint and test output from before and after.",
  "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

A pull request with four changed files in the fixture's shape: the list component, the query options with the corrected last-page check, the test setup with the new stub, and a test file for the list. The description shows the one-line change to `getNextPageParam` with the API response that exposed it, since that fix is independent of the scrolling and a reviewer may want it even if they reject the rest.

It pastes the output of `yarn check-types`, `yarn lint` and `yarn vitest run` from before and after, the same commands `.github/workflows/react-vite-ci.yml` runs in `apps/react-vite`, and lists the existing tests that exercise the comments list so the reviewer can see they were not edited. It states what the tests cannot show: jsdom does no layout, so the stub proves the wiring and not the scroll position at which a real browser fires.

The reviewer runs the app, scrolls a long discussion and watches the network panel for one request per page, then deletes a comment. Deleting invalidates the key, and an infinite query refetches every page it has loaded, one after another, so a reader who scrolled far triggers that many requests. The description says so and names `maxPages` as the option that bounds it, without adding it.

## Run it on every Linear issue labelled agent

Create an automation in the Project that has the repository, with this prompt and a `linear` trigger on `linear.issue.labeled`. The issue that fired it is placed after the prompt as data; nothing is substituted into the prompt, so phrase it to say that the issue names the list to convert and that the comments list is only the default. The trigger needs a Linear connection for the member the automation runs as, set up in the console under Settings → Connections.

Each labelled issue becomes one run and one pull request, up to the automation's max runs per hour; an issue past that waits as a queued run. To drive it from a script instead, send this body to `POST /o/{org}/sessions` once per list, with a `request_id` that is a UUID v5 of the repository and the component path so a retry returns the run it already started.

## Why run it on Rush?

The risk in this change is a loop of requests, and you find that by running the list against an API and counting calls. In its own sandbox the agent installs the app, runs the suite with the mock API the repository ships, and counts requests for the empty and the long list. Those commands and their output are kept in the transcript at `GET /o/{org}/sessions/{id}/messages`, so the claim that an empty discussion makes one request is something a reviewer can trace to a test run.

The sandbox also has a browser, which matters for a feature whose tests cannot do layout. The agent can build the app, open a long discussion and scroll it, and attach what it saw to the pull request. Because each run has its own checkout, converting three lists is three runs at once and three small pull requests.

## Frequently asked questions

### Does it need a library such as react-intersection-observer?

No. One effect and one ref cover it, and the prompt forbids a new dependency. If your app already uses such a hook elsewhere, say so and the agent uses it for consistency.

### Why keep the button at all?

It is the path that works without the observer: keyboard navigation, assistive technology that does not scroll, and any environment where the callback never fires. It costs nothing to keep, since it sits inside the element being observed and is only visible for the moment before the next page loads.

### What happens to the cache when someone adds a comment?

The same as before. `useCreateComment` and `useDeleteComment` invalidate `['comments', discussionId]`, and TanStack Query refetches the pages already loaded, in order. The agent does not change that; it reports the number of pages a refetch can touch and points at `maxPages` if you want a ceiling.

### Will it work with cursor-based APIs?

Yes. Only `getNextPageParam` and `initialPageParam` differ: the next page param is the cursor from the last page, and the list ends when the API returns none. The sentinel, the observer and the tests are the same, and the agent reads your API's response shape from the code before writing them.

## More TanStack Query jobs

- [Add Offline Support to a TanStack Query React App](https://getrush.ai/run/add-offline-support/tanstack-query/)
- [Add Optimistic Updates to a TanStack Query App](https://getrush.ai/run/add-optimistic-ui/tanstack-query/)
- [Add Query Prefetching to a TanStack Router App](https://getrush.ai/run/add-query-prefetching/tanstack-query/)

## The same job on other stacks

- [Add Infinite Scroll to an htmx App](https://getrush.ai/run/add-infinite-scroll/htmx/)

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

- [Add an Ingress Template to a Helm Chart](https://getrush.ai/run/add-ingress/helm/)
- [Add an Ingress to a Kubernetes App](https://getrush.ai/run/add-ingress/kubernetes/)

## 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/)
