Open History to see the last commit
1---
2id: query-cancellation
3title: Query Cancellation
4---
5β
6TanStack Query provides each query function with an [`AbortSignal` instance](https://developer.mozilla.org/docs/Web/API/AbortSignal). When a query becomes out-of-date or inactive, this `signal` will become aborted. This means that all queries are cancellable, and you can respond to the cancellation inside your query function if desired. The best part about this is that it allows you to continue to use normal async/await syntax while getting all the benefits of automatic cancellation.
7β
8## Default behavior
9β
10By default, queries that unmount or become unused before their promises are resolved are _not_ cancelled. This means that after the promise has resolved, the resulting data will be available in the cache. This is helpful if you've started receiving a query, but then unmount the component before it finishes. If you mount the component again and the query has not been garbage collected yet, data will be available.
11β
12However, if you consume the `AbortSignal`, the Promise will be cancelled (e.g. aborting the fetch) and therefore, also the Query must be cancelled. Cancelling the query will result in its state being _reverted_ to its previous state.
13β
14## Using `HttpClient`
15β
16```ts
17import { HttpClient } from '@angular/common/http'
18import { injectQuery } from '@tanstack/angular-query-experimental'
19β
20postQuery = injectQuery(() => ({
21 enabled: this.postId() > 0,
22 queryKey: ['post', this.postId()],
23 queryFn: async (context): Promise<Post> => {
24 const abort$ = fromEvent(context.signal, 'abort')
25 return lastValueFrom(this.getPost$(this.postId()).pipe(takeUntil(abort$)))
26 },
27}))
28```
29β
30## Using `fetch`
31β
32[//]: # 'Example2'
33β
34```ts
35query = injectQuery(() => ({
36 queryKey: ['todos'],
37 queryFn: async ({ signal }) => {
38 const todosResponse = await fetch('/todos', {
39 // Pass the signal to one fetch
40 signal,
41 })
42 const todos = await todosResponse.json()
43β
44 const todoDetails = todos.map(async ({ details }) => {
45 const response = await fetch(details, {
46 // Or pass it to several
47 signal,
48 })
49 return response.json()
50 })
51β
52 return Promise.all(todoDetails)
53 },
54}))
55```
56β
57[//]: # 'Example2'
58β
59## Using `axios`
60β
61[//]: # 'Example3'
62β
63```tsx
64import axios from 'axios'
65β
66const query = injectQuery(() => ({
67 queryKey: ['todos'],
68 queryFn: ({ signal }) =>
69 axios.get('/todos', {
70 // Pass the signal to `axios`
71 signal,
72 }),
73}))
74```
75β
76[//]: # 'Example3'
77β
78## Manual Cancellation
79β
80You might want to cancel a query manually. For example, if the request takes a long time to finish, you can allow the user to click a cancel button to stop the request. To do this, you just need to call `queryClient.cancelQueries({ queryKey })`, which will cancel the query and revert it back to its previous state. If you have consumed the `signal` passed to the query function, TanStack Query will additionally also cancel the Promise.
81β
82[//]: # 'Example7'
83β
84```angular-ts
85@Component({
86 standalone: true,
87 template: `<button (click)="onCancel()">Cancel</button>`,
88})
89export class TodosComponent {
90 query = injectQuery(() => ({
91 queryKey: ['todos'],
92 queryFn: async ({ signal }) => {
93 const resp = await fetch('/todos', { signal })
94 return resp.json()
95 },
96 }))
97β
98 queryClient = inject(QueryClient)
99β
100 onCancel() {
101 this.queryClient.cancelQueries(['todos'])
102 }
103}
104```
105β
106[//]: # 'Example7'