Skip to content

Commit

Permalink
fix(query-core): respect initialData for queryClient.ensureQueryData (#…
Browse files Browse the repository at this point in the history
…8425)

* fix(query-core): respect initialData for queryClient.ensureQueryData

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`

* refactor: simplify condition
  • Loading branch information
TkDodo authored Dec 10, 2024
1 parent 27ce0b6 commit 465906a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 12 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
23 changes: 11 additions & 12 deletions packages/query-core/src/queryClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,23 +145,22 @@ 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))
) {
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<
Expand Down

0 comments on commit 465906a

Please sign in to comment.