0Pricing
tRPC End-to-End Type Safe APIs · Lección

Actualizaciones optimistas con mutaciones de tRPC

Haga que su interfaz de Next.js parezca instantánea aplicando actualizaciones optimistas a las mutaciones de tRPC y revirtiéndolas correctamente cuando falle una solicitud.

Actualizaciones optimistas con mutaciones de tRPC es una lección gratuita de tRPC End-to-End Type Safe APIs en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de tRPC End-to-End Type Safe APIs, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de tRPC End-to-End Type Safe APIs incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

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.

Preguntas frecuentes

¿La lección «Actualizaciones optimistas con mutaciones de tRPC» es gratis?

Sí — el texto completo de «Actualizaciones optimistas con mutaciones de tRPC» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de tRPC End-to-End Type Safe APIs, actualiza a CoddyKit PRO. El curso de tRPC End-to-End Type Safe APIs incluye 4 lecciones en total.

¿Qué aprenderé en «Actualizaciones optimistas con mutaciones de tRPC»?

Haga que su interfaz de Next.js parezca instantánea aplicando actualizaciones optimistas a las mutaciones de tRPC y revirtiéndolas correctamente cuando falle una solicitud. Practicas tRPC End-to-End Type Safe APIs con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar tRPC End-to-End Type Safe APIs?

No se requiere experiencia previa. tRPC End-to-End Type Safe APIs en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.

¿Cuánto tiempo toma la lección «Actualizaciones optimistas con mutaciones de tRPC»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de tRPC End-to-End Type Safe APIs?

Sí. Cada lección de tRPC End-to-End Type Safe APIs incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. tRPC con Next.js App Router
  2. Integración avanzada con React Query
  3. Componentes de servidor y obtención de datos con tRPC
  4. Actualizaciones optimistas con mutaciones de tRPC
← Volver a tRPC End-to-End Type Safe APIs