Open History to see the last commit
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 })
54)
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>
144)
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```