MCPcopy Create free account
hub / github.com/TanStack/query / ensureQueryData

Method ensureQueryData

packages/query-core/src/queryClient.ts:208–234  ·  view source on GitHub ↗

* Returns the cached data of a query, or fetches it if there is none. With `revalidateIfStale`, * stale cached data is also refetched in the background. * @param options - The query options. If the query has no cached data yet, it is fetched with * these options. * @returns A promise tha

(
    options: EnsureQueryDataOptions<TQueryFnData, TError, TData, TQueryKey>,
  )

Source from the content-addressed store, hash-verified

206 * @deprecated Use queryClient.query({ ...options, staleTime: 'static' }) instead. This method will be removed in the next major version.
207 */
208 ensureQueryData<
209 TQueryFnData,
210 TError = DefaultError,
211 TData = TQueryFnData,
212 TQueryKey extends QueryKey = QueryKey,
213 >(
214 options: EnsureQueryDataOptions<TQueryFnData, TError, TData, TQueryKey>,
215 ): Promise<TData> {
216 const defaultedOptions = this.defaultQueryOptions(options)
217 const query = this.#queryCache.build(this, defaultedOptions)
218 const cachedData = query.state.data
219
220 if (cachedData === undefined) {
221 // oxlint-disable-next-line tanstack-query/no-restricted-syntax
222 return this.fetchQuery(options)
223 }
224
225 if (
226 options.revalidateIfStale &&
227 query.isStaleByTime(resolveQueryValue(defaultedOptions.staleTime, query))
228 ) {
229 // oxlint-disable-next-line tanstack-query/no-restricted-syntax
230 void this.prefetchQuery(defaultedOptions)
231 }
232
233 return Promise.resolve(cachedData)
234 }
235
236 /**
237 * Imperative (non-reactive) way to retrieve the cached data of multiple queries at once.

Callers 3

Calls 6

defaultQueryOptionsMethod · 0.95
fetchQueryMethod · 0.95
prefetchQueryMethod · 0.95
resolveQueryValueFunction · 0.90
isStaleByTimeMethod · 0.80
buildMethod · 0.45

Tested by

no test coverage detected