Skip to content

Commit c77c133

Browse files
committed
fix(core): never revert to undefined data
1 parent f1e608b commit c77c133

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

packages/query-core/src/__tests__/queryClient.test.tsx

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
22
import { queryKey, sleep } from '@tanstack/query-test-utils'
33
import {
4+
CancelledError,
45
MutationObserver,
56
QueryClient,
67
QueryObserver,
@@ -1060,6 +1061,24 @@ describe('queryClient', () => {
10601061
status: 'error',
10611062
})
10621063
})
1064+
1065+
test('should throw CancelledError when initial fetch is cancelled', async () => {
1066+
const key = queryKey()
1067+
1068+
const promise = queryClient.fetchQuery({
1069+
queryKey: key,
1070+
queryFn: async () => {
1071+
await sleep(50)
1072+
return 25
1073+
},
1074+
})
1075+
1076+
await vi.advanceTimersByTimeAsync(10)
1077+
1078+
await queryClient.cancelQueries({ queryKey: key })
1079+
1080+
await expect(promise).rejects.toBeInstanceOf(CancelledError)
1081+
})
10631082
})
10641083

10651084
describe('refetchQueries', () => {

packages/query-core/src/query.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -558,7 +558,11 @@ export class Query<
558558
fetchStatus: 'idle' as const,
559559
})
560560
// transform error into reverted state data
561-
return this.state.data!
561+
// if the initial fetch was cancelled, we have no data, so we have
562+
// to get into error state with the CancelledError
563+
if (this.state.data !== undefined) {
564+
return this.state.data
565+
}
562566
}
563567
}
564568
this.#dispatch({

0 commit comments

Comments
 (0)