Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

query-cancellation.md

193 lines5.2 KB

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>
187```
188​
189[//]: # 'Example7'
190​
191## Limitations
192​
193Cancellation does not work when working with `Suspense` hooks: `useSuspenseQuery`, `useSuspenseQueries` and `useSuspenseInfiniteQuery`.