Aborting Procedure Calls
@trpc/react-query
By default, tRPC does not cancel requests on unmount. If you want to opt into this behavior, you can provide abortOnUnmount
in your configuration.
client.tsts
// @filename: utils.tsimport {createTRPCReact } from '@trpc/react-query';export consttrpc =createTRPCReact <AppRouter >();trpc .createClient ({// ...abortOnUnmount : true,});
client.tsts
// @filename: utils.tsimport {createTRPCReact } from '@trpc/react-query';export consttrpc =createTRPCReact <AppRouter >();trpc .createClient ({// ...abortOnUnmount : true,});
You may also override this behavior at the request level.
client.tsts
// @filename: pages/posts/[id].tsximport {trpc } from '~/utils/trpc';constPostViewPage :NextPageWithLayout = () => {constid =useRouter ().query .id as string;constpostQuery =trpc .post .byId .useQuery ({id }, {trpc : {abortOnUnmount : true } });return (...)}
client.tsts
// @filename: pages/posts/[id].tsximport {trpc } from '~/utils/trpc';constPostViewPage :NextPageWithLayout = () => {constid =useRouter ().query .id as string;constpostQuery =trpc .post .byId .useQuery ({id }, {trpc : {abortOnUnmount : true } });return (...)}
Note: @tanstack/react-query only allows aborting queries.
@trpc/client
tRPC adheres to the industry standard when it comes to aborting procedures. All you have to do is pass an AbortSignal
to the query-options and then call its parent AbortController
's abort
method.
utils.tsts
// @filename: server.tsimport {createTRPCProxyClient ,httpBatchLink } from '@trpc/client';import type {AppRouter } from 'server.ts';constproxy =createTRPCProxyClient <AppRouter >({links : [httpBatchLink ({url : 'http://localhost:3000/trpc',}),],});constac = newAbortController ();constquery =proxy .userById .query ('id_bilbo', {signal :ac .signal });// Cancellingac .abort ();console .log (query .status );
utils.tsts
// @filename: server.tsimport {createTRPCProxyClient ,httpBatchLink } from '@trpc/client';import type {AppRouter } from 'server.ts';constproxy =createTRPCProxyClient <AppRouter >({links : [httpBatchLink ({url : 'http://localhost:3000/trpc',}),],});constac = newAbortController ();constquery =proxy .userById .query ('id_bilbo', {signal :ac .signal });// Cancellingac .abort ();console .log (query .status );
Note: The vanilla tRPC client allows aborting both queries and mutations