By default, queries that become inactive before their promises are resolved are simply ignored instead of canceled. Why is this?
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):
axios
import { CancelToken } from 'axios'const query = useQuery('todos', () => {// Create a new CancelToken source for this requestconst source = CancelToken.source()const promise = axios.get('/todos', {// Pass the source token to your requestcancelToken: source.token,})// Cancel the request if React Query calls the `promise.cancel` methodpromise.cancel = () => {source.cancel('Query was cancelled by React Query')}return promise})
fetch
const query = useQuery('todos', () => {// Create a new AbortController instance for this requestconst controller = new AbortController()// Get the abortController's signalconst signal = controller.signalconst promise = fetch('/todos', {method: 'get',// Pass the signal to your requestsignal,})// Cancel the request if React Query calls the `promise.cancel` methodpromise.cancel = () => controller.abort()return promise})
The latest TanStack news, articles, and resources, sent to your inbox.