diff --git a/packages/query-core/src/__tests__/queryClient.test.tsx b/packages/query-core/src/__tests__/queryClient.test.tsx index ec01f5e272..11f2129db9 100644 --- a/packages/query-core/src/__tests__/queryClient.test.tsx +++ b/packages/query-core/src/__tests__/queryClient.test.tsx @@ -477,6 +477,21 @@ describe('queryClient', () => { }), ).resolves.toEqual('new') }) + + test('should not fetch with initialDat', async () => { + const key = queryKey() + const queryFn = vi.fn().mockImplementation(() => Promise.resolve('data')) + + await expect( + queryClient.ensureQueryData({ + queryKey: [key, 'id'], + queryFn, + initialData: 'initial', + }), + ).resolves.toEqual('initial') + + expect(queryFn).toHaveBeenCalledTimes(0) + }) }) describe('ensureInfiniteQueryData', () => { diff --git a/packages/query-core/src/queryClient.ts b/packages/query-core/src/queryClient.ts index a62a6ee9c2..72c3a42cbf 100644 --- a/packages/query-core/src/queryClient.ts +++ b/packages/query-core/src/queryClient.ts @@ -145,23 +145,22 @@ export class QueryClient { >( options: EnsureQueryDataOptions, ): Promise { - const cachedData = this.getQueryData(options.queryKey) + const defaultedOptions = this.defaultQueryOptions(options) + const query = this.#queryCache.build(this, defaultedOptions) + const cachedData = query.state.data if (cachedData === undefined) { return this.fetchQuery(options) - } else { - const defaultedOptions = this.defaultQueryOptions(options) - const query = this.#queryCache.build(this, defaultedOptions) - - if ( - options.revalidateIfStale && - query.isStaleByTime(resolveStaleTime(defaultedOptions.staleTime, query)) - ) { - void this.prefetchQuery(defaultedOptions) - } + } - return Promise.resolve(cachedData) + if ( + options.revalidateIfStale && + query.isStaleByTime(resolveStaleTime(defaultedOptions.staleTime, query)) + ) { + void this.prefetchQuery(defaultedOptions) } + + return Promise.resolve(cachedData) } getQueriesData<