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β
8The `AbortController` API is available in [most runtime environments](https://developer.mozilla.org/docs/Web/API/AbortController#browser_compatibility), but if your runtime environment does not support it, you will need to provide a polyfill. There are [several available](https://www.npmjs.com/search?q=abortcontroller%20polyfill).
9β
10## Default behavior
11β
12By 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.
13β
14However, 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.
15β
16## Using `fetch`
17β
18[//]: # 'Example'
19β
20```tsx
21const query = useQuery({
22 queryKey: ['todos'],
23 queryFn: async ({ signal }) => {
24 const todosResponse = await fetch('/todos', {
25 // Pass the signal to one fetch
26 signal,
27 })
28 const todos = await todosResponse.json()
29β
30 const todoDetails = todos.map(async ({ details }) => {
31 const response = await fetch(details, {
32 // Or pass it to several
33 signal,
34 })
35 return response.json()
36 })
37β
38 return Promise.all(todoDetails)
39 },
40})
41```
42β
43[//]: # 'Example'
44β
45## Using `axios` [v0.22.0+](https://github.com/axios/axios/releases/tag/v0.22.0)
46β
47[//]: # 'Example2'
48β
49```tsx
50import axios from 'axios'
51β
52const query = useQuery({
53 queryKey: ['todos'],
54 queryFn: ({ signal }) =>
55 axios.get('/todos', {
56 // Pass the signal to `axios`
57 signal,
58 }),
59})
60```
61β
62[//]: # 'Example2'
63β
64### Using `axios` with version lower than v0.22.0
65β
66[//]: # 'Example3'
67β
68```tsx
69import axios from 'axios'
70β
71const query = useQuery({
72 queryKey: ['todos'],
73 queryFn: ({ signal }) => {
74 // Create a new CancelToken source for this request
75 const CancelToken = axios.CancelToken
76 const source = CancelToken.source()
77β
78 const promise = axios.get('/todos', {
79 // Pass the source token to your request
80 cancelToken: source.token,
81 })
82β
83 // Cancel the request if TanStack Query signals to abort
84 signal?.addEventListener('abort', () => {
85 source.cancel('Query was cancelled by TanStack Query')
86 })
87β
88 return promise
89 },
90})
91```
92β
93[//]: # 'Example3'
94β
95## Using `XMLHttpRequest`
96β
97[//]: # 'Example4'
98β
99```tsx
100const query = useQuery({
101 queryKey: ['todos'],
102 queryFn: ({ signal }) => {
103 return new Promise((resolve, reject) => {
104 var oReq = new XMLHttpRequest()
105 oReq.addEventListener('load', () => {
106 resolve(JSON.parse(oReq.responseText))
107 })
108 signal?.addEventListener('abort', () => {
109 oReq.abort()
110 reject()
111 })
112 oReq.open('GET', '/todos')
113 oReq.send()
114 })
115 },
116})
117```
118β
119[//]: # 'Example4'
120β
121## Using `graphql-request`
122β
123An `AbortSignal` can be set in the client `request` method.
124β
125[//]: # 'Example5'
126β
127```tsx
128const client = new GraphQLClient(endpoint)
129β
130const query = useQuery({
131 queryKey: ['todos'],
132 queryFn: ({ signal }) => {
133 client.request({ document: query, signal })
134 },
135})
136```
137β
138[//]: # 'Example5'
139β
140## Using `graphql-request` with version lower than v4.0.0
141β
142An `AbortSignal` can be set in the `GraphQLClient` constructor.
143β
144[//]: # 'Example6'
145β
146```tsx
147const query = useQuery({
148 queryKey: ['todos'],
149 queryFn: ({ signal }) => {
150 const client = new GraphQLClient(endpoint, {
151 signal,
152 })
153 return client.request(query, variables)
154 },
155})
156```
157β
158[//]: # 'Example6'
159β
160## Manual Cancellation
161β
162You 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.
163β
164[//]: # 'Example7'
165β
166```tsx
167const query = useQuery({
168 queryKey: ['todos'],
169 queryFn: async ({ signal }) => {
170 const resp = await fetch('/todos', { signal })
171 return resp.json()
172 },
173})
174β
175const queryClient = useQueryClient()
176β
177return (
178 <button
179 onClick={(e) => {
180 e.preventDefault()
181 queryClient.cancelQueries({ queryKey: ['todos'] })
182 }}
183 >
184 Cancel
185 </button>
186)
187```
188β
189[//]: # 'Example7'
190β
191## `Cancel Options`
192β
193Cancel options are used to control the behavior of query cancellation operations.
194β
195```tsx
196// Cancel specific queries silently
197await queryClient.cancelQueries({ queryKey: ['posts'] }, { silent: true })
198```
199β
200A cancel options object supports the following properties:
201β
202- `silent?: boolean`
203 - When set to `true`, suppresses propagation of `CancelledError` to observers (e.g., `onError` callbacks) and related notifications, and returns the retry promise instead of rejecting.
204 - Defaults to `false`
205- `revert?: boolean`
206 - When set to `true`, restores the queryβs state (data and status) from immediately before the in-flight fetch, sets `fetchStatus` back to `idle`, and only throws if there was no prior data.
207 - Defaults to `true`
208β
209## Limitations
210β
211[//]: # 'Limitations'
212β
213Cancellation does not work when working with `Suspense` hooks: `useSuspenseQuery`, `useSuspenseQueries` and `useSuspenseInfiniteQuery`.
214β
215[//]: # 'Limitations'