UNPKG

@trpc/next

Version:

The tRPC Next.js library

42 lines (32 loc) • 1.91 kB
# Aborting Procedure Calls > Cancel in-flight requests when a component unmounts with the abortOnUnmount option on a query From https://trpc.io/docs/client/nextjs/pages-router/aborting-procedure-calls 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: ```tsx no-check title="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`](https://trpc.io/docs/client/links/splitLink). > [!NOTE] > `createTRPCNext`'s `abortOnUnmount` in `config` set this for every query. Like the rest of `createTRPCNext`, it's deprecated. See [Moving from `createTRPCNext`](https://trpc.io/docs/client/nextjs/pages-router/setup#moving-from-createtrpcnext).