Shadcn Table with TanStack Query Mutations
Edit a name, status or budget and the table changes at once while the save runs in the background. Each row shows its own Saving… state, a rejected save puts that row back and offers Retry, and the list is refetched once every save has landed.
$ npx shadcn add https://www.shad-table.dev/r/query-mutations-table.json| Project | Status | Budget | Save status |
|---|---|---|---|
How it works
1.The query cache is the table data
useQuery loads the projects and its data goes straight into useReactTable. There is no copy in component state to keep in sync: an optimistic write, a rollback or a refetch all change the cache, and the table re-renders from it.
const projects = useProjects(api)const table = useReactTable({data: projects.data ?? [],columns,getRowId: (row) => row.id,getCoreRowModel: getCoreRowModel(),meta,})
2.Optimistic edits, rolled back one row at a time
onMutate cancels any refetch in flight, so it cannot land on top of the edit, then writes the change into the cache and keeps the row as it was. If the save fails, only that row is restored, and only the fields that no newer edit has changed since. Restoring a snapshot of the whole list would also undo edits to other rows that are still saving.
onMutate: async ({ id, patch }) => {await client.cancelQueries({ queryKey: projectsKey })const previous = client.getQueryData<Project[]>(projectsKey)?.find((project) => project.id === id)setProject(client, id, (project) => ({ ...project, ...patch }))return { previous }},
3.Invalidate once, after the last save
The server has the last word (here it tidies names and bumps a version), so its reply replaces the row. The list is refetched after a save settles, but only when no other save is still running: refetching earlier would bring back old values over edits that have not been confirmed yet.
onSettled: () => {if (pendingSaves(client) === 1) {return client.invalidateQueries({ queryKey: projectsKey })}},
4.Per-row "Saving…" from the mutation cache
useMutationState reads every save from the mutation cache, so no state is kept by hand. The latest save for each row decides what it shows: a spinner while pending, or the error with a Retry that sends the same change again. Try a budget over $50,000, or turn on "Make saves fail".
const mutations = useMutationState({filters: { mutationKey: updateKey },select: (m) => toSave(m),})