All jobs

Add Optimistic Updates to a TanStack Query App

Yes. An agent adds onMutate, onError and onSettled with a cache rollback to the mutation hooks, proves it against a failing mock server, and opens a PR.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

The agent reads the data layer before it touches the cache, because an optimistic update has to write the exact shape the query holds. In a codebase laid out like alan2207/bulletproof-react's apps/react-vite, every feature keeps its hooks under features/<name>/api/. For comments, get-comments.ts exports getInfiniteCommentsQueryOptions(discussionId) with the key ['comments', discussionId], a queryFn that pages through GET /comments, and getNextPageParam reading meta.page against meta.totalPages. create-comment.ts and delete-comment.ts wrap useMutation and, in onSuccess, call queryClient.invalidateQueries on that key, then the caller's own onSuccess. lib/react-query.ts sets retry: false and a one-minute staleTime, and exports a MutationConfig type the hooks take. The list renders from commentsQuery.data?.pages.flatMap((page) => page.data) in comments-list.tsx, keyed by comment.id || index.

The change lives in the two mutation hooks and nowhere in the components. useDeleteComment gains onMutate: cancel in-flight queries for the key, read the current infinite data with getQueryData, write a copy with the comment filtered out of every page's data and meta.total reduced by one, and return the snapshot. onError puts the snapshot back with setQueryData; onSettled invalidates the key so the server's answer wins either way. The existing onSuccess call-through to the caller stays, so delete-comment.tsx still shows its notification. useCreateComment does the same in the other direction: it prepends a comment to the first page's data with a temporary id from nanoid, which package.json already has, the body from the input, and the current user as author, since the list renders author.firstName.

Two details come from reading rather than from the TanStack docs. The infinite data has the shape { pages, pageParams }, so the optimistic write maps over pages and leaves pageParams alone; writing a flat array would make flatMap throw on the next render. And comments-list.tsx keys list items by comment.id || index, which with a temporary id is fine, but the Authorization policy check reads comment.author, so the optimistic comment must carry a real user object, which useUser() from lib/auth provides inside the hook.

In its sandbox the agent runs yarn install and yarn test, then adds a test beside app/routes/app/discussions/__tests__/discussion.test.tsx, which already creates and deletes a comment through the mock server. The new test uses msw's server.use from testing/mocks to make DELETE /comments/:id answer 500 once, clicks Delete Comment, asserts the comment leaves the list before the networkDelay of 200 ms elapses, then asserts it is back after the error. A second test asserts a created comment appears before the mock server answers. It runs yarn check-types and yarn lint, because MutationConfig is typed, and quotes all three results.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "Add optimistic updates to the comment mutations in this React app. Read src/lib/react-query.ts, src/features/comments/api/get-comments.ts, create-comment.ts, delete-comment.ts, src/features/comments/components/comments-list.tsx, src/types/api.ts, src/testing/mocks/handlers/comments.ts and src/app/routes/app/discussions/__tests__/discussion.test.tsx first. In useDeleteComment and useCreateComment add onMutate that cancels the comments query, snapshots the infinite data and writes the optimistic pages, onError that restores the snapshot, and onSettled that invalidates the key; keep the caller's onSuccess working and change no component. Use nanoid for the temporary id and the current user as author. Run yarn install and yarn test, then add tests that a delete leaves the list before the mock server answers and returns after a 500, and that a create appears before the answer. Run yarn check-types and yarn lint. Open a pull request quoting the results.",
  "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 two hook files and adds two tests. create-comment.ts and delete-comment.ts each gain onMutate, onError and onSettled and keep their onSuccess call-through; no component changes, because the list already renders whatever the cache holds. The description quotes yarn test with the two new tests named, and yarn check-types and yarn lint clean.

The description walks through one delete in three states: the comment gone the moment the button is clicked, the server's 500 putting it back, and the final invalidation refetching the page. It names the infinite data shape it wrote and why the temporary comment carries a full author.

Before merging, a reviewer decides whether the other features want the same treatment, since discussions/api has the same invalidateQueries pattern across five hooks, and whether a failed optimistic delete should show the error notification the api-client interceptor already raises or a second, more specific one.

Run it on every Linear issue labelled agent

Latency complaints arrive one feature at a time, so a team routes them by label. An automation in the app's Project with the prompt above and a linear trigger on linear.issue.labeled for the label agent starts a run when someone files "deleting a comment takes a second to disappear" and labels it. The trigger adds the issue after the prompt, so the run reads which feature the issue names and changes that feature's hooks.

Each run opens its own pull request on its own branch and links the issue. A feature whose hooks already roll back gets a description saying so and no code change, and one whose query is not infinite gets the flat-array version of the same write, because the run reads the query options before it writes.

The use case this job follows, with its automation and trigger: Turn a Linear label into a PR.

Why run it on Rush?

An optimistic update is twenty lines that have to match the cache's shape exactly, and the shape of an infinite query is the one most people get wrong on the first try. The symptom is a blank list after a click, which no unit test on the hook alone will catch. In a Rush sandbox the agent reads the query options and the component that renders them, writes to the real shape, and proves both the fast path and the rollback against the mock server before anyone reviews.

The record of the run keeps the test runs, and the pull request quotes them, so the reviewer reads a delete disappearing and coming back on a 500 rather than trusting the hook by inspection. Across every feature in the app, and every app a team keeps on this pattern, the same request runs in parallel, one sandbox and one pull request each.

Frequently asked questions

Why change the hooks and not the components?

The components already render from the cache and already pass an onSuccess for their notifications. Putting the optimistic write in useDeleteComment and useCreateComment keeps every caller on the new behaviour with no component edits, and the existing onSuccess call-through is kept so the notification still fires.

What happens when the server rejects the change?

onError writes the snapshot taken in onMutate back with setQueryData, so the comment reappears, and onSettled invalidates the key, so the next render reflects the server. The new test makes DELETE /comments/:id answer 500 once and asserts the comment returns.

Why does the optimistic comment need an author?

comments-list.tsx renders author.firstName and runs the comment:delete policy on the comment, both of which read author. The hook takes the signed-in user from useUser and puts it on the temporary comment, so the list renders it the same way it will render the server's copy.

Does this work with the infinite query's pages?

Yes, and that is the part the agent reads for. The cache holds { pages, pageParams }, so the write maps over pages, edits each page's data and meta.total, and leaves pageParams untouched. A flat array in that slot would break the flatMap in the list on the next render.

More TanStack Query jobs

The same job on other stacks

Keep reading