Web / TanStack Interview Questions
How do you implement optimistic updates with TanStack Query?
Optimistic updates change the UI immediately before the server responds. On error the UI rolls back to the snapshot saved in onMutate.
const { mutate:toggleTodo }=useMutation({ mutationFn: (todo:Todo)=> fetch(`/api/todos/${todo.id}`,{ method:"PATCH", body:JSON.stringify({done:!todo.done}), }).then(r=>r.json()), onMutate: async (todo)=>{ // Cancel in-flight fetches so they don't overwrite our update await qc.cancelQueries({queryKey:["todos"]}) const prev=qc.getQueryData<Todo[]>(["todos"]) qc.setQueryData<Todo[]>(["todos"], old=>old?.map(t=>t.id===todo.id?{...t,done:!t.done}:t)??[]) return { prev } }, onError: (_,__,ctx)=>{ if(ctx?.prev) qc.setQueryData(["todos"],ctx.prev) }, onSettled: ()=>{ qc.invalidateQueries({queryKey:["todos"]}) }, })
More Related questions...