Browse documentation
Lesson 06 · Write data

Write back from a Server Function

Validate input at the network boundary, model write state with a mutation, then immutably update Query cache from the server response.

TanStack QueryApplied24 minREV 02Markdown .md
After this lesson

Implement a create flow with pending, error, and success states.

01

Protect the server boundary first

Client types do not replace runtime validation. A POST Server Function uses validator before the handler to turn unknown data into trusted input; real apps should also authenticate and authorize here.

src/features/issues/issues.tsts
export const createIssue = createServerFn({ method: 'POST' })
  .validator((input: { title: string }) => {
    const title = input.title.trim()
    if (title.length < 3) throw new Error('Title is too short')
    return { title }
  })
  .handler(async ({ data }) => saveIssue(data))
02

Update the single source of truth from the response

useMutation owns the write lifecycle. On success, update cache from the complete server response; return a new array instead of pushing into the old cached value.

src/routes/issues/index.tsxtsx
const queryClient = useQueryClient()
const mutation = useMutation({
  mutationFn: (input: CreateIssueInput) =>
    createIssue({ data: input }),
  onSuccess: (issue) => {
    queryClient.setQueryData<Issue[]>(['issues'], (current = []) => [
      issue,
      ...current,
    ])
  },
})
PRACTICE

Turn this lesson into a verifiable skill

Completion checkpoint

List and detail caches agree after a successful write, while failed writes do not leave unconfirmed data visible.

Exercise

After creating an issue, seed its detail cache and invalidate only the affected list prefix.

Verification

Exercise success and failure; success should seed detail data, while failure should preserve the previous cache value.

Common pitfalls
  • Invalidating the entire query cache after every mutation.
  • Assuming the server response is identical to the submitted input.
SOURCE REFERENCES · CHECKED 2026-08-03https://tanstack.com/start/latest/docs/framework/react/guide/server-functionshttps://tanstack.com/query/latest/docs/framework/react/guides/mutationshttps://tanstack.com/query/latest/docs/framework/react/guides/updates-from-mutation-responses
TanStack Atlas

Original bilingual knowledge · verified against primary sources

Friend linksGitHub