Skip to content
tRPC

Partners

Aborting Procedure Calls

Cancel in-flight requests when a component unmounts with the abortOnUnmount option on a query

By default, tRPC doesn't cancel a request when the component that made it unmounts. To cancel it, set abortOnUnmount in the trpc option of the query:

pages/posts/[id].tsx
import { skipToken, useQuery } from '@tanstack/react-query';
import { useRouter } from 'next/router';
import { useTRPC } from '../../utils/trpc';

export default function PostViewPage() {
  const router = useRouter();
  // `query.id` is undefined until the router is ready
  const id = router.query.id;
  const trpc = useTRPC();
  const postQuery = useQuery(
    trpc.post.byId.queryOptions(typeof id === 'string' ? { id } : skipToken, {
      trpc: { abortOnUnmount: true },
    }),
  );

  switch (postQuery.status) {
    case 'pending':
      return <p>Loading...</p>;
    case 'error':
      return <p>Error: {postQuery.error.message}</p>;
    case 'success':
      return <h1>{postQuery.data.title}</h1>;
  }
}

There's no global switch: createTRPCContext() takes no options, so set it on each query that needs it. It works for queryOptions and infiniteQueryOptions, since TanStack React Query only cancels queries.

With httpBatchLink or httpBatchStreamLink, the HTTP request only stops once every query in its batch is cancelled. Cancelling one query alone just drops its result. To stop the request for a single query, send it through httpLink, for instance with a splitLink.