The standard way to abort a query using react-query is to use the AbortController to abort the fetch request (reference https://tanstack.com/query/v4/docs/react/guides/query-cancellation):
const query = useQuery({
queryKey: ['todos'],
queryFn: async ({ signal }) => {
const resp = await fetch('/todos', { signal })
return resp.json()
},
})
const queryClient = useQueryClient()
return (
<button
onClick={(e) => {
e.preventDefault()
queryClient.cancelQueries({ queryKey: ['todos'] })
}}
>
Cancel
</button>
)
You can use an abort controller with this as well (reference https://trpc.io/docs/client/vanilla/aborting-procedure-calls):
// 1. Create an AbortController instance - this is a standard javascript API
const ac = new AbortController();
// 2. Pass the signal to a query or mutation
const query = proxy.userById.query('id_bilbo', { signal: ac.signal });
// 3. Cancel the request if needed
ac.abort();
This is where I am lost. Here we do not have the access to the underlying fetch
(which we did in standard React Query) and there is no way to pass in a signal that I could find in the docs. You can see the docs here : https://trpc.io/docs/client/react/aborting-procedure-calls
It should work by passing abortOnUnmount: true
(as shown in the docs link you posted). Contrary to the name, this just forwards the AbortSignal
to fetch
, which means requests will also be cancelled if you call trpc.useUtils().userById.cancel()