使用 tRPC 变更实现乐观更新
为 tRPC 变更应用乐观更新,让 Next.js UI 感觉即时,并在请求失败时整洁地回滚。
使用 tRPC 变更实现乐观更新 是 CoddyKit 上的免费 tRPC End-to-End Type Safe APIs 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 tRPC End-to-End Type Safe APIs 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 tRPC End-to-End Type Safe APIs 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
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.
常见问题解答
「使用 tRPC 变更实现乐观更新」课时是免费的吗?
是的 — 「使用 tRPC 变更实现乐观更新」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 tRPC End-to-End Type Safe APIs 课程的其余内容,请升级到 CoddyKit PRO。 tRPC End-to-End Type Safe APIs 课程共包含 4 节课。
「使用 tRPC 变更实现乐观更新」这节课中我会学到什么?
为 tRPC 变更应用乐观更新,让 Next.js UI 感觉即时,并在请求失败时整洁地回滚。 你通过在浏览器中直接运行的动手代码来练习 tRPC End-to-End Type Safe APIs,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 tRPC End-to-End Type Safe APIs 需要有经验吗?
无需任何先前经验。CoddyKit 上的 tRPC End-to-End Type Safe APIs 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「使用 tRPC 变更实现乐观更新」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 tRPC End-to-End Type Safe APIs 课中编写并运行代码吗?
能。每节 tRPC End-to-End Type Safe APIs 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 在 Next.js 应用路由器中使用 tRPC
- 高级 React Query 集成
- 服务器组件与 tRPC 数据获取
- 使用 tRPC 变更实现乐观更新