You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
By default, queries that unmount or become unused before their promises are resolved are simply ignored instead of canceled. Why is this?
6
+
[_Previous method requiring a `cancel` function_](#old-cancel-function)
7
7
8
-
- For most applications, ignoring out-of-date queries is sufficient.
9
-
- Cancellation APIs may not be available for every query function.
10
-
- If cancellation APIs are available, they typically vary in implementation between utilities/libraries (eg. Fetch vs Axios vs XMLHttpRequest).
8
+
React 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 allow 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.
11
9
12
-
But don't worry! If your queries are high-bandwidth or potentially very expensive to download, React Query exposes a generic way to **cancel** query requests using a cancellation token or other related API. To 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):
10
+
The `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
+
## Using `fetch`
13
+
14
+
```js
15
+
constquery=useQuery('todos', async ({ signal }) => {
// Cancel the request if React Query calls the `promise.cancel` method
30
-
promise.cancel= () => {
64
+
// Cancel the request if React Query signals to abort
65
+
signal?.addEventListener('abort', () => {
31
66
source.cancel('Query was cancelled by React Query')
32
-
}
67
+
})
33
68
34
69
return promise
35
70
})
36
71
```
37
72
38
-
## Using `fetch`
73
+
## Using `XMLHttpRequest`
74
+
75
+
```js
76
+
constquery=useQuery('todos', ({ signal }) => {
77
+
returnnewPromise((resolve, reject) => {
78
+
var oReq =newXMLHttpRequest()
79
+
oReq.addEventListener('load', () => {
80
+
resolve(JSON.parse(oReq.responseText))
81
+
})
82
+
signal?.addEventListener('abort', () => {
83
+
oReq.abort()
84
+
reject()
85
+
})
86
+
oReq.open('GET', '/todos')
87
+
oReq.send()
88
+
})
89
+
})
90
+
```
91
+
92
+
## Manual Cancellation
93
+
94
+
You 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)`. If `promise.cancel` is available or you have consumed the `singal` passed to the query function then React Query will cancel the request.
95
+
96
+
```js
97
+
const [queryKey] =useState('todos')
98
+
99
+
constquery=useQuery(queryKey, await ({ signal }) => {
100
+
constresp=fetch('/todos', { signal })
101
+
returnresp.json()
102
+
})
103
+
104
+
constqueryClient=useQueryClient()
105
+
106
+
return (
107
+
<button onClick={(e) => {
108
+
e.preventDefault()
109
+
queryClient.cancelQueries(queryKey)
110
+
}}>Cancel</button>
111
+
)
112
+
```
113
+
114
+
## Old `cancel` function
115
+
116
+
Don'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 [stardardized](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.
117
+
118
+
To 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).
119
+
120
+
## Using `axios` with `cancel` function
39
121
40
122
```js
123
+
importaxiosfrom'axios'
124
+
41
125
constquery=useQuery('todos', () => {
42
-
// Create a new AbortController instance for this request
43
-
constcontroller=newAbortController()
44
-
// Get the abortController's signal
45
-
constsignal=controller.signal
126
+
// Create a new CancelToken source for this request
127
+
constCancelToken=axios.CancelToken
128
+
constsource=CancelToken.source()
46
129
47
-
constpromise=fetch('/todos', {
48
-
method:'get',
49
-
// Pass the signal to your request
50
-
signal,
130
+
constpromise=axios.get('/todos', {
131
+
// Pass the source token to your request
132
+
cancelToken:source.token,
51
133
})
52
134
53
135
// Cancel the request if React Query calls the `promise.cancel` method
54
-
promise.cancel= () =>controller.abort()
136
+
promise.cancel= () => {
137
+
source.cancel('Query was cancelled by React Query')
138
+
}
55
139
56
140
return promise
57
141
})
58
142
```
59
143
60
-
## Manual Cancellation
61
-
62
-
You 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)`. If `promise.cancel` is available, React Query will cancel the request.
144
+
## Using `fetch` with `cancel` function
63
145
64
146
```js
65
-
const [queryKey] =useState('todos')
66
-
67
-
constquery=useQuery(queryKey, () => {
147
+
constquery=useQuery('todos', () => {
148
+
// Create a new AbortController instance for this request
0 commit comments