tRPCミューテーションの楽観的更新
tRPCミューテーションに楽観的更新を適用してNext.js UIを即時に反応させ、リクエスト失敗時には適切にロールバックします。
「tRPCミューテーションの楽観的更新」はCoddyKit上の無料tRPC End-to-End Type Safe APIsレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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ミューテーションの楽観的更新」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応の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を演習し、24時間対応の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 App RouterでtRPCを使う
- React Queryの高度な統合
- サーバーコンポーネントとtRPCによるデータ取得
- tRPCミューテーションの楽観的更新