Pembaruan Optimistis dengan Mutasi tRPC
Buat UI Next.js Anda terasa instan dengan menerapkan pembaruan optimistis pada mutasi tRPC dan mengembalikannya dengan rapi saat permintaan gagal.
Pembaruan Optimistis dengan Mutasi tRPC adalah pelajaran tRPC End-to-End Type Safe APIs gratis di CoddyKit. Ini adalah pelajaran 4 dari 4. Kamu bisa membaca pelajaran lengkapnya di bawah secara gratis — lalu praktikkan langsung di browser dengan editor kode bawaan dan tutor AI 24/7. Ini adalah bagian dari jalur belajar tRPC End-to-End Type Safe APIs, dan progresmu tersinkronisasi di web dan aplikasi CoddyKit. Kursus tRPC End-to-End Type Safe APIs mencakup 4 pelajaran total.
Bagian dari pelajaran ini belum diterjemahkan dan ditampilkan dalam bahasa Inggris.
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.
Pertanyaan yang Sering Diajukan
Apakah pelajaran “Pembaruan Optimistis dengan Mutasi tRPC” gratis?
Ya — teks lengkap “Pembaruan Optimistis dengan Mutasi tRPC” gratis dibaca di sini di web. Untuk praktiknya secara interaktif (editor kode bawaan dan tutor AI 24/7) dan buka sisa kursus tRPC End-to-End Type Safe APIs, upgrade ke CoddyKit PRO. Kursus tRPC End-to-End Type Safe APIs mencakup 4 pelajaran total.
Apa yang akan aku pelajari di “Pembaruan Optimistis dengan Mutasi tRPC”?
Buat UI Next.js Anda terasa instan dengan menerapkan pembaruan optimistis pada mutasi tRPC dan mengembalikannya dengan rapi saat permintaan gagal. Kamu berlatih tRPC End-to-End Type Safe APIs dengan kode praktik yang langsung kamu jalankan di browser, dan tutor AI 24/7 menjawab pertanyaanmu saat kamu mengerjakan pelajaran ini.
Apakah aku perlu pengalaman untuk memulai tRPC End-to-End Type Safe APIs?
Tidak diperlukan pengalaman sebelumnya. tRPC End-to-End Type Safe APIs di CoddyKit dirancang untuk pemula hingga pelajar tingkat lanjut, jadi kamu bisa memulai di sini atau dari awal dan belajar sesuai kecepatan kamu sendiri. Ini adalah pelajaran 4 dari 4.
Berapa lama pelajaran “Pembaruan Optimistis dengan Mutasi tRPC” memakan waktu?
Sebagian besar pelajaran CoddyKit memakan waktu sekitar 5–10 menit. Setiap pelajaran ringkas dan interaktif, jadi kamu membuat kemajuan stabil dan melanjutkan dari tempat kamu tinggalkan di web dan aplikasi.
Bisakah aku menulis dan menjalankan kode dalam pelajaran tRPC End-to-End Type Safe APIs ini?
Ya. Setiap pelajaran tRPC End-to-End Type Safe APIs menyertakan editor kode bawaan, jadi kamu menulis dan menjalankan kode nyata langsung di browser dan mendapatkan umpan balik AI instan — tidak diperlukan penyiapan lokal.
Semua pelajaran dalam kursus ini
- tRPC dengan App Router Next.js
- Integrasi React Query Tingkat Lanjut
- Komponen Server dan Pengambilan Data tRPC
- Pembaruan Optimistis dengan Mutasi tRPC