Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions packages/query-core/src/__tests__/queryClient.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
import { queryKey, sleep } from '@tanstack/query-test-utils'
import {
CancelledError,
MutationObserver,
QueryClient,
QueryObserver,
Expand Down Expand Up @@ -1060,6 +1061,24 @@ describe('queryClient', () => {
status: 'error',
})
})

test('should throw CancelledError when initial fetch is cancelled', async () => {
const key = queryKey()

const promise = queryClient.fetchQuery({
queryKey: key,
queryFn: async () => {
await sleep(50)
return 25
},
})

await vi.advanceTimersByTimeAsync(10)

await queryClient.cancelQueries({ queryKey: key })

await expect(promise).rejects.toBeInstanceOf(CancelledError)
})
})

describe('refetchQueries', () => {
Expand Down
6 changes: 5 additions & 1 deletion packages/query-core/src/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -558,7 +558,11 @@ export class Query<
fetchStatus: 'idle' as const,
})
// transform error into reverted state data
return this.state.data!
// if the initial fetch was cancelled, we have no data, so we have
// to get into error state with the CancelledError
if (this.state.data !== undefined) {
return this.state.data
}
}
}
this.#dispatch({
Expand Down
Loading