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

query-cancellation.md

139 lines4.7 KB

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 })
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>
139```