Skip to content

Commit

Permalink
fix(query-core): respect initialData for queryClient.ensureQueryData
Browse files Browse the repository at this point in the history
we used to call `getQueryData` before queryCache.build(), but building is what creates the query and potentially adds initialData. I tried to make that more obvious by reading directly from `query.state.data`
  • Loading branch information
TkDodo committed Dec 10, 2024
1 parent 27ce0b6 commit 2040a6c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
15 changes: 15 additions & 0 deletions packages/query-core/src/__tests__/queryClient.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
7 changes: 3 additions & 4 deletions packages/query-core/src/queryClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,14 +145,13 @@ export class QueryClient {
>(
options: EnsureQueryDataOptions<TQueryFnData, TError, TData, TQueryKey>,
): Promise<TData> {
const cachedData = this.getQueryData<TData>(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))
Expand Down

0 comments on commit 2040a6c

Please sign in to comment.