Optimistische Aktualisierungen mit tRPC-Mutationen
Lassen Sie Ihre Next.js-UI durch optimistische Aktualisierungen bei tRPC-Mutationen sofort reagieren und rollen Sie Änderungen bei einem fehlgeschlagenen Request sauber zurück.
Optimistische Aktualisierungen mit tRPC-Mutationen ist eine kostenlose tRPC End-to-End Type Safe APIs-Lektion auf CoddyKit. Dies ist Lektion 4 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des tRPC End-to-End Type Safe APIs-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der tRPC End-to-End Type Safe APIs-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
Why Optimistic Updates
When a user clicks a button, waiting for the server feels slow. Optimistic updates update the UI immediately, assuming the mutation will succeed, then reconcile with the real server response.
tRPC pairs perfectly with React Query, which handles the cache mechanics for you.
Anatomy of a tRPC Mutation
A mutation hook gives you mutate, isPending, and lifecycle callbacks: onMutate, onError, onSettled.
Optimistic logic lives in these callbacks.
const mutation = trpc.todo.add.useMutation();
mutation.mutate({ text: 'Buy milk' });Getting the Query Utils
To touch the cache you need the tRPC utils object. It exposes per-query cancel, get, and set methods that mirror React Query.
const utils = trpc.useUtils();Cancel In-Flight Queries
Inside onMutate, first cancel any outgoing refetches so they do not overwrite your optimistic value.
onMutate: async (newTodo) => {
await utils.todo.list.cancel();
}Snapshot the Previous Value
Save the current cache so you can roll back if the mutation fails.
const previous = utils.todo.list.getData();Apply the Optimistic Change
Write the expected new state into the cache with setData. The UI updates instantly.
utils.todo.list.setData(undefined, (old) =>
old ? [...old, { id: 'temp', text: newTodo.text }] : old
);Return a Rollback Context
Return the snapshot from onMutate. React Query passes it to onError as context.
return { previous };Roll Back on Error
If the server rejects the mutation, restore the snapshot so the UI matches reality.
onError: (err, newTodo, context) => {
utils.todo.list.setData(undefined, context?.previous);
}Reconcile on Settled
Whether it succeeds or fails, invalidate the query in onSettled so the cache resyncs with the server truth.
onSettled: () => {
utils.todo.list.invalidate();
}Putting It Together
The full optimistic mutation wires every callback in one place.
const add = trpc.todo.add.useMutation({
onMutate: async (n) => {
await utils.todo.list.cancel();
const previous = utils.todo.list.getData();
utils.todo.list.setData(undefined, (o) => o ? [...o, { id: 'temp', text: n.text }] : o);
return { previous };
},
onError: (e, n, ctx) => utils.todo.list.setData(undefined, ctx?.previous),
onSettled: () => utils.todo.list.invalidate(),
});Best Practices
Keep optimistic updates safe:
- Always cancel in-flight queries first
- Always snapshot before mutating
- Use a temporary id you can replace later
- Invalidate on settle to avoid drift
Quick Check
Test your optimistic update knowledge.
Recap
You implemented optimistic updates with tRPC and React Query:
- Cancel queries, snapshot, then setData in
onMutate - Restore the snapshot in
onError - Invalidate in
onSettled
Your UI now feels instant while staying consistent with the server.
Häufig gestellte Fragen
Ist die Lektion „Optimistische Aktualisierungen mit tRPC-Mutationen“ kostenlos?
Ja — der vollständige Text von „Optimistische Aktualisierungen mit tRPC-Mutationen“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des tRPC End-to-End Type Safe APIs-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der tRPC End-to-End Type Safe APIs-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Optimistische Aktualisierungen mit tRPC-Mutationen“?
Lassen Sie Ihre Next.js-UI durch optimistische Aktualisierungen bei tRPC-Mutationen sofort reagieren und rollen Sie Änderungen bei einem fehlgeschlagenen Request sauber zurück. Du übst tRPC End-to-End Type Safe APIs mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um tRPC End-to-End Type Safe APIs zu starten?
Keine Vorkenntnisse erforderlich. tRPC End-to-End Type Safe APIs auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 4 von 4.
Wie lange dauert die Lektion „Optimistische Aktualisierungen mit tRPC-Mutationen“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser tRPC End-to-End Type Safe APIs-Lektion Code schreiben und ausführen?
Ja. Jede tRPC End-to-End Type Safe APIs-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- tRPC mit dem Next.js App Router
- Erweiterte React-Query-Integration
- Server Components und tRPC-Datenabruf
- Optimistische Aktualisierungen mit tRPC-Mutationen