Open History to see the last commit
1---
2id: query-cancellation
3title: Query Cancellation
4---
5β
6React 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.
7β
8The `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).
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` 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.
15β
16## Using `fetch`
17β
18```tsx
19const query = useQuery(['todos'], async ({ signal }) => {
20 const todosResponse = await fetch('/todos', {
21 // Pass the signal to one fetch
22 signal,
23 })
24 const todos = await todosResponse.json()
25β
26 const todoDetails = todos.map(async ({ details } => {
27 const response = await fetch(details, {
28 // Or pass it to several
29 signal,
30 })
31 return response.json()
32 })
33β
34 return Promise.all(todoDetails)
35})
36```
37β
38## Using `axios`
39β
40### Using `axios` [v0.22.0+](https://github.com/axios/axios/releases/tag/v0.22.0)
41β
42```tsx
43import axios from 'axios'
44β
45const query = useQuery(['todos'], ({ signal }) =>
46 axios.get('/todos', {
47 // Pass the signal to `axios`
48 signal,
49 })
50)
51```
52β
53### Using an `axios` version less than v0.22.0
54β
55```tsx
56import axios from 'axios'
57β
58const query = useQuery(['todos'], ({ signal }) => {
59 // Create a new CancelToken source for this request
60 const CancelToken = axios.CancelToken
61 const source = CancelToken.source()
62β
63 const promise = axios.get('/todos', {
64 // Pass the source token to your request
65 cancelToken: source.token,
66 })
67β
68 // Cancel the request if React Query signals to abort
69 signal?.addEventListener('abort', () => {
70 source.cancel('Query was cancelled by React Query')
71 })
72β
73 return promise
74})
75```
76β
77## Using `XMLHttpRequest`
78β
79```tsx
80const query = useQuery(['todos'], ({ signal }) => {
81 return new Promise((resolve, reject) => {
82 var oReq = new XMLHttpRequest()
83 oReq.addEventListener('load', () => {
84 resolve(JSON.parse(oReq.responseText))
85 })
86 signal?.addEventListener('abort', () => {
87 oReq.abort()
88 reject()
89 })
90 oReq.open('GET', '/todos')
91 oReq.send()
92 })
93})
94```
95β
96## Using `graphql-request`
97β
98An `AbortSignal` can be set in the client `request` method.
99β
100```tsx
101const client = new GraphQLClient(endpoint)
102β
103const query = useQuery(['todos'], ({ signal }) => {
104 client.request({ document: query, signal })
105})
106```
107β
108## Using `graphql-request` version less than v4.0.0
109β
110An `AbortSignal` can be set in the `GraphQLClient` constructor.
111β
112```tsx
113const query = useQuery(['todos'], ({ signal }) => {
114 const client = new GraphQLClient(endpoint, {
115 signal,
116 });
117 return client.request(query, variables)
118})
119```
120β
121## Manual Cancellation
122β
123You 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.
124β
125```tsx
126const query = useQuery(['todos'], async ({ signal }) => {
127 const resp = await fetch('/todos', { signal })
128 return resp.json()
129})
130β
131const queryClient = useQueryClient()
132β
133return (
134 <button onClick={(e) => {
135 e.preventDefault()
136 queryClient.cancelQueries(['todos'])
137 }}>Cancel</button>
138)
139```