T
TanStack2y ago
fair-rose

How does one use the abort signal in combination with tanstack-query

Say I have the following route:
export const orderQueryOptions = (orderId: string) =>
queryOptions({
queryKey: ["order", { orderId }],
queryFn: ({ signal }) =>
api.get(`api/v1/orders/${orderId}`, { signal }).json<Order>(),
});

export const Route = createFileRoute("/_authenticated/orders/$id")({
component: ShowOrder,
loader: ({ context, params }) =>
context.queryClient.ensureQueryData(orderQueryOptions(params.id)),
});
export const orderQueryOptions = (orderId: string) =>
queryOptions({
queryKey: ["order", { orderId }],
queryFn: ({ signal }) =>
api.get(`api/v1/orders/${orderId}`, { signal }).json<Order>(),
});

export const Route = createFileRoute("/_authenticated/orders/$id")({
component: ShowOrder,
loader: ({ context, params }) =>
context.queryClient.ensureQueryData(orderQueryOptions(params.id)),
});
How do I use the abort signal in both the loader and the queryFn
4 Replies
extended-salmon
extended-salmon2y ago
AbortSignal.any(loaderContext.abortController.signal, signal)
extended-salmon
extended-salmon2y ago
When you are using TanStack Query, you are opting into offloading the data-fetching and caching over to TSQ. So, what you are doing in the loader for your Route definition, really is just triggering ensureQueryData method in TSQ. I'd recommend not mixing the AbortControllers from TSQ and TSR, as you may trigger an un-intended state in Query.
optimistic-gold
optimistic-gold2y ago
agree. just take the signal that you get into the queryFn and pass it to your api. Nothing else should be needed
fair-rose
fair-roseOP2y ago
Makes sense, thanks!

Did you find this page helpful?