Skip to content

Commit 4d01e1f

Browse files
committed
Merge branch 'master' into beta
2 parents ba9e936 + 6e2e37e commit 4d01e1f

File tree

2 files changed

+35
-5
lines changed

2 files changed

+35
-5
lines changed

docs/src/pages/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+
```

src/core/query.ts

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -187,14 +187,12 @@ export class Query<TData = unknown, TError = unknown, TQueryFnData = TData> {
187187
// Get the new data
188188
let data = functionalUpdate(updater, prevData)
189189

190-
// Structurally share data between prev and new data if needed
191-
if (this.options.structuralSharing !== false) {
192-
data = replaceEqualDeep(prevData, data)
193-
}
194-
195190
// Use prev data if an isDataEqual function is defined and returns `true`
196191
if (this.options.isDataEqual?.(prevData, data)) {
197192
data = prevData as TData
193+
} else if (this.options.structuralSharing !== false) {
194+
// Structurally share data between prev and new data if needed
195+
data = replaceEqualDeep(prevData, data)
198196
}
199197

200198
// Set data and mark it as cached

0 commit comments

Comments
 (0)