Skip to content

Commit 11bf7a4

Browse files
docs: Update query-cancellation.md (#1328)
* Update query-cancellation.md Add sample code to manually cancel a query. * Update query-cancellation.md * Update query-cancellation.md * Update query-cancellation.md
1 parent ae10094 commit 11bf7a4

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

docs/src/pages/docs/guides/query-cancellation.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,3 +55,35 @@ const query = useQuery('todos', () => {
5555
return promise
5656
})
5757
```
58+
59+
## Manual Cancellation
60+
61+
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 `cache.cancelQueries(key)`. If `promise.cancel` is available, React Query will cancel the request.
62+
63+
```js
64+
const [queryKey] = useState('todos')
65+
66+
const query = useQuery(queryKey, () => {
67+
const controller = new AbortController()
68+
const signal = controller.signal
69+
70+
const promise = fetch('/todos', {
71+
method: 'get',
72+
signal,
73+
})
74+
75+
// Cancel the request if React Query calls the `promise.cancel` method
76+
promise.cancel = () => controller.abort()
77+
78+
return promise
79+
})
80+
81+
const cache = useQueryCache();
82+
83+
return (
84+
<button onClick={(e) => {
85+
e.preventDefault();
86+
cache.cancelQueries(queryKey);
87+
}}>Cancel</button>
88+
)
89+
```

0 commit comments

Comments
 (0)