Query Cancellation

· abundance's blog


TanStack Query provides each query function with an AbortSignal instance. 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.

The AbortController API is available in most runtime environments, but if your runtime environment does not support it, you will need to provide a polyfill. There are several available.

Default behavior #

By 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.

However, if you consume the AbortSignal, 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.

Using fetch #

 1const query = useQuery({
 2  queryKey: ['todos'],
 3  queryFn: async ({ signal }) => {
 4    const todosResponse = await fetch('/todos', {
 5      // Pass the signal to one fetch
 6      signal,
 7    })
 8    const todos = await todosResponse.json()
 9
10    const todoDetails = todos.map(async ({ details }) => {
11      const response = await fetch(details, {
12        // Or pass it to several
13        signal,
14      })
15      return response.json()
16    })
17
18    return Promise.all(todoDetails)
19  },
20})

Using axios v0.22.0+ #

 1import axios from 'axios'
 2
 3const query = useQuery({
 4  queryKey: ['todos'],
 5  queryFn: ({ signal }) =>
 6    axios.get('/todos', {
 7      // Pass the signal to `axios`
 8      signal,
 9    }),
10})

Using axios with version lower than v0.22.0 #

 1import axios from 'axios'
 2
 3const query = useQuery({
 4  queryKey: ['todos'],
 5  queryFn: ({ signal }) => {
 6    // Create a new CancelToken source for this request
 7    const CancelToken = axios.CancelToken
 8    const source = CancelToken.source()
 9
10    const promise = axios.get('/todos', {
11      // Pass the source token to your request
12      cancelToken: source.token,
13    })
14
15    // Cancel the request if TanStack Query signals to abort
16    signal?.addEventListener('abort', () => {
17      source.cancel('Query was cancelled by TanStack Query')
18    })
19
20    return promise
21  },
22})

Using XMLHttpRequest #

 1const query = useQuery({
 2  queryKey: ['todos'],
 3  queryFn: ({ signal }) => {
 4    return new Promise((resolve, reject) => {
 5      var oReq = new XMLHttpRequest()
 6      oReq.addEventListener('load', () => {
 7        resolve(JSON.parse(oReq.responseText))
 8      })
 9      signal?.addEventListener('abort', () => {
10        oReq.abort()
11        reject()
12      })
13      oReq.open('GET', '/todos')
14      oReq.send()
15    })
16  },
17})

Using graphql-request #

An AbortSignal can be set in the client request method.

1const client = new GraphQLClient(endpoint)
2
3const query = useQuery({
4  queryKey: ['todos'],
5  queryFn: ({ signal }) => {
6    client.request({ document: query, signal })
7  },
8})

Using graphql-request with version lower than v4.0.0 #

An AbortSignal can be set in the GraphQLClient constructor.

1const query = useQuery({
2  queryKey: ['todos'],
3  queryFn: ({ signal }) => {
4    const client = new GraphQLClient(endpoint, {
5      signal,
6    })
7    return client.request(query, variables)
8  },
9})

Manual Cancellation #

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({ queryKey }), which will cancel the query and revert it back to its previous state. If you have consumed the signal passed to the query function, TanStack Query will additionally also cancel the Promise.

 1const query = useQuery({
 2  queryKey: ['todos'],
 3  queryFn: async ({ signal }) => {
 4    const resp = await fetch('/todos', { signal })
 5    return resp.json()
 6  },
 7})
 8
 9const queryClient = useQueryClient()
10
11return (
12  <button
13    onClick={(e) => {
14      e.preventDefault()
15      queryClient.cancelQueries({ queryKey: ['todos'] })
16    }}
17  >
18    Cancel
19  </button>
20)