0Pricing
tRPC End-to-End Type Safe APIs · Aula

Atualizações otimistas com mutações tRPC

Faça sua interface Next.js parecer instantânea aplicando atualizações otimistas às mutações tRPC e revertendo-as corretamente quando uma solicitação falhar.

Atualizações otimistas com mutações tRPC é uma aula grátis de tRPC End-to-End Type Safe APIs no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de tRPC End-to-End Type Safe APIs, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de tRPC End-to-End Type Safe APIs inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em 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.

Perguntas Frequentes

A aula “Atualizações otimistas com mutações tRPC” é grátis?

Sim — o texto completo de “Atualizações otimistas com mutações tRPC” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de tRPC End-to-End Type Safe APIs, atualize para CoddyKit PRO. O curso de tRPC End-to-End Type Safe APIs inclui 4 aulas no total.

O que vou aprender em “Atualizações otimistas com mutações tRPC”?

Faça sua interface Next.js parecer instantânea aplicando atualizações otimistas às mutações tRPC e revertendo-as corretamente quando uma solicitação falhar. Você pratica tRPC End-to-End Type Safe APIs com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar tRPC End-to-End Type Safe APIs?

Nenhuma experiência prévia é necessária. tRPC End-to-End Type Safe APIs no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Atualizações otimistas com mutações tRPC”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de tRPC End-to-End Type Safe APIs?

Sim. Cada aula de tRPC End-to-End Type Safe APIs inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. tRPC com o roteador de aplicações do Next.js
  2. Integração avançada com React Query
  3. Componentes de servidor e busca de dados com tRPC
  4. Atualizações otimistas com mutações tRPC
← Voltar para tRPC End-to-End Type Safe APIs