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

Method ensureQueryData

packages/query-core/src/queryClient.ts:211–237  ·  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

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