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

query-cancellation.md

197 lines6.9 KB

1---
2id: query-cancellation
3title: Query Cancellation
4---
5​
6[_Previous method requiring a `cancel` function_](#old-cancel-function)
7​
8React Query provides each query function with an [`AbortSignal` instance](https://developer.mozilla.org/docs/Web/API/AbortSignal), **if it's available in your runtime environment**. 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. Additionally, this solution works better with TypeScript than the old solution.
9​
10The `AbortController` API is available in [most runtime environments](https://developer.mozilla.org/docs/Web/API/AbortController#browser_compatibility), but if the runtime environment does not support it then the query function will receive `undefined` in its place. You may choose to polyfill the `AbortController` API if you wish, there are [several available](https://www.npmjs.com/search?q=abortcontroller%20polyfill).
11​
12**NOTE:** This feature was introduced at version `3.30.0`. If you are using an older version, you will need to either upgrade (recommended) or use the [old `cancel` function](#old-cancel-function).
13​
14## Default behavior
15​
16By 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.
17​
18However, if you consume the `AbortSignal` or attach a `cancel` function to your Promise, 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.
19​
20## Using `fetch`
21​
22```js
23const query = useQuery('todos', 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## Using `axios`
43​
44### Using `axios` [v0.22.0+](https://github.com/axios/axios/releases/tag/v0.22.0)
45​
46```js
47import axios from 'axios'
48​
49const query = useQuery('todos', ({ signal }) =>
50 axios.get('/todos', {
51 // Pass the signal to `axios`
52 signal,
53 })
55```
56​
57### Using an `axios` version less than v0.22.0
58​
59```js
60import axios from 'axios'
61​
62const query = useQuery('todos', ({ signal }) => {
63 // Create a new CancelToken source for this request
64 const CancelToken = axios.CancelToken
65 const source = CancelToken.source()
66​
67 const promise = axios.get('/todos', {
68 // Pass the source token to your request
69 cancelToken: source.token,
70 })
71​
72 // Cancel the request if React Query signals to abort
73 signal?.addEventListener('abort', () => {
74 source.cancel('Query was cancelled by React Query')
75 })
76​
77 return promise
78})
79```
80​
81## Using `XMLHttpRequest`
82​
83```js
84const query = useQuery('todos', ({ signal }) => {
85 return new Promise((resolve, reject) => {
86 var oReq = new XMLHttpRequest()
87 oReq.addEventListener('load', () => {
88 resolve(JSON.parse(oReq.responseText))
89 })
90 signal?.addEventListener('abort', () => {
91 oReq.abort()
92 reject()
93 })
94 oReq.open('GET', '/todos')
95 oReq.send()
96 })
97})
98```
99​
100## Using `graphql-request`
101​
102An `AbortSignal` can be set in the client `request` method.
103​
104```js
105const client = new GraphQLClient(endpoint)
106​
107const query = useQuery('todos', ({ signal }) => {
108 client.request({ document: query, signal })
109})
110```
111​
112## Using `graphql-request` version less than v4.0.0
113​
114An `AbortSignal` can be set in the `GraphQLClient` constructor.
115​
116```js
117const query = useQuery('todos', ({ signal }) => {
118 const client = new GraphQLClient(endpoint, {
119 signal,
120 });
121 return client.request(query, variables)
122})
123```
124​
125## Manual Cancellation
126​
127You 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(key)`, which will cancel the query and revert it back to its previous state. If `promise.cancel` is available, or you have consumed the `signal` passed to the query function, React Query will additionally also cancel the Promise.
128​
129```js
130const [queryKey] = useState('todos')
131​
132const query = useQuery(queryKey, async ({ signal }) => {
133 const resp = await fetch('/todos', { signal })
134 return resp.json()
135})
136​
137const queryClient = useQueryClient()
138​
139return (
140 <button onClick={(e) => {
141 e.preventDefault()
142 queryClient.cancelQueries(queryKey)
143 }}>Cancel</button>
145```
146​
147## Old `cancel` function
148​
149Don't worry! The previous cancellation functionality will continue to work. But we do recommend that you move away from [the withdrawn cancelable promise proposal](https://github.com/tc39/proposal-cancelable-promises) to the [new `AbortSignal` interface](#_top) which has been [standardized](https://dom.spec.whatwg.org/#interface-abortcontroller) as a general purpose construct for aborting ongoing activities in [most browsers](https://caniuse.com/abortcontroller) and in [Node](https://nodejs.org/api/globals.html#globals_class_abortsignal). The old cancel function might be removed in a future major version.
150​
151To integrate with this feature, attach a `cancel` function to the promise returned by your query that implements your request cancellation. When a query becomes out-of-date or inactive, this `promise.cancel` function will be called (if available).
152​
153## Using `axios` with `cancel` function
154​
155```js
156import axios from 'axios'
157​
158const query = useQuery('todos', () => {
159 // Create a new CancelToken source for this request
160 const CancelToken = axios.CancelToken
161 const source = CancelToken.source()
162​
163 const promise = axios.get('/todos', {
164 // Pass the source token to your request
165 cancelToken: source.token,
166 })
167​
168 // Cancel the request if React Query calls the `promise.cancel` method
169 promise.cancel = () => {
170 source.cancel('Query was cancelled by React Query')
171 }
172​
173 return promise
174})
175```
176​
177## Using `fetch` with `cancel` function
178​
179```js
180const query = useQuery('todos', () => {
181 // Create a new AbortController instance for this request
182 const controller = new AbortController()
183 // Get the abortController's signal
184 const signal = controller.signal
185​
186 const promise = fetch('/todos', {
187 method: 'get',
188 // Pass the signal to your request
189 signal,
190 })
191​
192 // Cancel the request if React Query calls the `promise.cancel` method
193 promise.cancel = () => controller.abort()
194​
195 return promise
196})
197```