Open History to see the last commit
1import { hashQueryKeyByOptions, matchQuery } from './utils'
2import { Query } from './query'
3import { notifyManager } from './notifyManager'
4import { Subscribable } from './subscribable'
5import type { QueryFilters } from './utils'
6import type { Action, QueryState } from './query'
7import type {
8 DefaultError,
9 NotifyEvent,
10 QueryKey,
11 QueryOptions,
12 WithRequired,
13} from './types'
14import type { QueryClient } from './queryClient'
15import type { QueryObserver } from './queryObserver'
16β
17// TYPES
18β
19/**
20 * Global callbacks that fire for every query handled by a `QueryCache`,
21 * regardless of which component or observer triggered it. Unlike
22 * `QueryClient`'s `defaultOptions`, which a query can override, these callbacks
23 * are always called. Unlike `MutationCacheConfig`'s callbacks, these are
24 * fire-and-forget: their return value is not awaited before the query settles.
25 */
26export interface QueryCacheConfig {
27 /** Called when any query in the cache encounters an error. */
28 onError?: (
29 error: DefaultError,
30 query: Query<unknown, unknown, unknown>,
31 ) => void
32 /** Called when any query in the cache is successful. */
33 onSuccess?: (data: unknown, query: Query<unknown, unknown, unknown>) => void
34 /**
35 * Called when any query in the cache is settled, either successfully or with
36 * an error.
37 */
38 onSettled?: (
39 data: unknown | undefined,
40 error: DefaultError | null,
41 query: Query<unknown, unknown, unknown>,
42 ) => void
43}
44β
45interface NotifyEventQueryAdded extends NotifyEvent {
46 type: 'added'
47 query: Query<any, any, any, any>
48}
49β
50interface NotifyEventQueryRemoved extends NotifyEvent {
51 type: 'removed'
52 query: Query<any, any, any, any>
53}
54β
55interface NotifyEventQueryUpdated extends NotifyEvent {
56 type: 'updated'
57 query: Query<any, any, any, any>
58 action: Action<any, any>
59}
60β
61interface NotifyEventQueryObserverAdded extends NotifyEvent {
62 type: 'observerAdded'
63 query: Query<any, any, any, any>
64 observer: QueryObserver<any, any, any, any, any>
65}
66β
67interface NotifyEventQueryObserverRemoved extends NotifyEvent {
68 type: 'observerRemoved'
69 query: Query<any, any, any, any>
70 observer: QueryObserver<any, any, any, any, any>
71}
72β
73interface NotifyEventQueryObserverResultsUpdated extends NotifyEvent {
74 type: 'observerResultsUpdated'
75 query: Query<any, any, any, any>
76}
77β
78interface NotifyEventQueryObserverOptionsUpdated extends NotifyEvent {
79 type: 'observerOptionsUpdated'
80 query: Query<any, any, any, any>
81 observer: QueryObserver<any, any, any, any, any>
82}
83β
84/**
85 * The event passed to a `QueryCache` subscriber. Fired whenever a query is
86 * added or removed from the cache, its state is updated (e.g. via
87 * `query.setState` or `queryClient.removeQueries`), or one of its observers is
88 * added, removed, or has its results or options updated.
89 */
90export type QueryCacheNotifyEvent =
91 | NotifyEventQueryAdded
92 | NotifyEventQueryRemoved
93 | NotifyEventQueryUpdated
94 | NotifyEventQueryObserverAdded
95 | NotifyEventQueryObserverRemoved
96 | NotifyEventQueryObserverResultsUpdated
97 | NotifyEventQueryObserverOptionsUpdated
98β
99type QueryCacheListener = (event: QueryCacheNotifyEvent) => void
100β
101/** The store a `QueryCache` keeps its queries in, keyed by query hash. */
102export interface QueryStore {
103 /** Returns whether a query with the given hash is stored. */
104 has: (queryHash: string) => boolean
105 /** Stores a query under its hash. */
106 set: (queryHash: string, query: Query) => void
107 /** Returns the query with the given hash, if any. */
108 get: (queryHash: string) => Query | undefined
109 /** Removes the query with the given hash. */
110 delete: (queryHash: string) => void
111 /** Returns an iterator over all stored queries. */
112 values: () => IterableIterator<Query>
113}
114β
115// CLASS
116β
117/**
118 * The `QueryCache` is the storage mechanism for TanStack Query. It stores all
119 * the data, meta information, and state of the queries it contains.
120 *
121 * Normally, you will not interact with the `QueryCache` directly and instead
122 * use a `QueryClient` for a specific cache. You can subscribe to it (inherited
123 * from `Subscribable`) to be informed of safe/known updates to the cache, such
124 * as queries being added, removed, or updated β updates made outside of the
125 * cache's own tracked mechanisms (e.g. mutating a query's state object
126 * directly) do not notify subscribers.
127 *
128 * @example
129 * ;```ts
130 * const unsubscribe = queryCache.subscribe((event) => {
131 * console.log(event.type, event.query)
132 * })
133 * ```
134 */
135export class QueryCache extends Subscribable<QueryCacheListener> {
136 #queries: QueryStore
137β
138 constructor(public config: QueryCacheConfig = {}) {
139 super()
140 this.#queries = new Map<string, Query>()
141 }
142β
143 /**
144 * Returns the existing `Query` instance for the given options'
145 * `queryKey`/`queryHash`, or builds and adds a new one to the cache if none
146 * exists yet. Used by framework adapters and plugins (e.g.
147 * broadcast/persistence) that need to get-or-create a `Query` directly,
148 * bypassing the reactive `QueryObserver` machinery.
149 *
150 * @example
151 * ;```ts
152 * const queryCache = queryClient.getQueryCache()
153 *
154 * const query = queryCache.build(queryClient, {
155 * queryKey: ['posts'],
156 * queryFn: fetchPosts,
157 * })
158 * ```
159 *
160 * @param client - The client the query belongs to, used to default its
161 * options.
162 * @param options - The query options, including the `queryKey`. A new query
163 * is created with the options defaulted by
164 * {@link QueryClient#defaultQueryOptions}.
165 * @param state - The initial state of a newly created query, e.g. when
166 * hydrating. Ignored if the query already exists.
167 * @returns The existing or newly created query.
168 */
169 build<
170 TQueryFnData = unknown,
171 TError = DefaultError,
172 TData = TQueryFnData,
173 TQueryKey extends QueryKey = QueryKey,
174 >(
175 client: QueryClient,
176 options: WithRequired<
177 QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
178 'queryKey'
179 >,
180 state?: QueryState<TData, TError>,
181 ): Query<TQueryFnData, TError, TData, TQueryKey> {
182 const queryKey = options.queryKey
183 const queryHash =
184 options.queryHash ?? hashQueryKeyByOptions(queryKey, options)
185 let query = this.get<TQueryFnData, TError, TData, TQueryKey>(queryHash)
186β
187 if (!query) {
188 query = new Query({
189 client,
190 queryKey,
191 queryHash,
192 options: client.defaultQueryOptions(options),
193 state,
194 defaultOptions: client.getQueryDefaults(queryKey),
195 })
196 this.add(query)
197 }
198β
199 return query
200 }
201β
202 /**
203 * Adds a query to the cache.
204 *
205 * @param query - The query to add. If a query with the same hash is already
206 * cached, nothing happens.
207 * @internal
208 */
209 add(query: Query<any, any, any, any>): void {
210 if (!this.#queries.has(query.queryHash)) {
211 this.#queries.set(query.queryHash, query)
212β
213 this.notify({
214 type: 'added',
215 query,
216 })
217 }
218 }
219β
220 /**
221 * Destroys the given `Query` and removes it from the cache, notifying
222 * subscribers with a `'removed'` event. A no-op if the query is no longer the
223 * one currently stored under its hash (e.g. it was already replaced). Used by
224 * plugins (e.g. the broadcast client) that mirror removals across
225 * `QueryCache` instances.
226 *
227 * @example
228 * ;```ts
229 * const queryCache = queryClient.getQueryCache()
230 * const query = queryCache.find({ queryKey: ['posts'] })
231 *
232 * if (query) {
233 * queryCache.remove(query)
234 * }
235 * ```
236 *
237 * @param query - The query to remove.
238 */
239 remove(query: Query<any, any, any, any>): void {
240 const queryInMap = this.#queries.get(query.queryHash)
241β
242 if (queryInMap === query) {
243 query.destroy()
244 this.#queries.delete(query.queryHash)
245 this.notify({ type: 'removed', query })
246 }
247 }
248β
249 /**
250 * Removes all queries from the cache.
251 *
252 * @example
253 * ;```ts
254 * const queryCache = queryClient.getQueryCache()
255 *
256 * queryCache.clear()
257 * ```
258 */
259 clear(): void {
260 notifyManager.batch(() => {
261 this.getAll().forEach((query) => {
262 this.remove(query)
263 })
264 })
265 }
266β
267 /**
268 * Returns the `Query` instance stored under the given `queryHash`, or
269 * `undefined` if none exists. Unlike {@link QueryCache#find}, this looks up by
270 * the already-computed hash rather than by `QueryFilters`. Used by plugins
271 * (e.g. broadcast/hydration) that already have a hash to look up directly.
272 *
273 * @example
274 * ;```ts
275 * const queryCache = queryClient.getQueryCache()
276 * const queryHash = hashKey(['posts'])
277 *
278 * const query = queryCache.get(queryHash)
279 * ```
280 *
281 * @param queryHash - The hash of the query to look up.
282 * @returns The query stored under the hash, or `undefined`.
283 */
284 get<
285 TQueryFnData = unknown,
286 TError = DefaultError,
287 TData = TQueryFnData,
288 TQueryKey extends QueryKey = QueryKey,
289 >(
290 queryHash: string,
291 ): Query<TQueryFnData, TError, TData, TQueryKey> | undefined {
292 return this.#queries.get(queryHash) as
293 | Query<TQueryFnData, TError, TData, TQueryKey>
294 | undefined
295 }
296β
297 /**
298 * Returns all queries within the cache.
299 *
300 * @example
301 * ;```ts
302 * const queryCache = queryClient.getQueryCache()
303 *
304 * const queries = queryCache.getAll()
305 * ```
306 *
307 * @returns Every query in the cache.
308 */
309 getAll(): Array<Query> {
310 return [...this.#queries.values()]
311 }
312β
313 /**
314 * A slightly more advanced method that can be used to get an existing query
315 * instance from the cache. This instance not only contains all the state for
316 * the query, but all of the instances, and underlying guts of the query as
317 * well. If the query does not exist, `undefined` is returned.
318 *
319 * This is not typically needed for most applications, but can come in handy
320 * when needing more information about a query in rare scenarios (e.g. looking
321 * at `query.state.dataUpdatedAt` to decide whether a query is fresh enough to
322 * be used as an initial value).
323 *
324 * @example
325 * ;```ts
326 * const queryCache = queryClient.getQueryCache()
327 *
328 * const query = queryCache.find({ queryKey: ['posts'] })
329 * ```
330 *
331 * @param filters - The filters to match, including the required `queryKey`.
332 * `exact` defaults to `true`.
333 * @returns The first matching query, or `undefined`.
334 * @see {@link QueryCache#findAll}
335 */
336 find<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData>(
337 filters: WithRequired<QueryFilters, 'queryKey'>,
338 ): Query<TQueryFnData, TError, TData> | undefined {
339 const defaultedFilters = { exact: true, ...filters }
340β
341 return this.getAll().find((query) =>
342 matchQuery(defaultedFilters, query),
343 ) as Query<TQueryFnData, TError, TData> | undefined
344 }
345β
346 /**
347 * An even more advanced method that can be used to get existing query
348 * instances from the cache that partially match a query key. If no queries
349 * match, an empty array is returned.
350 *
351 * This is not typically needed for most applications, but can come in handy
352 * when needing more information about queries in rare scenarios.
353 *
354 * @example
355 * ;```ts
356 * const queryCache = queryClient.getQueryCache()
357 *
358 * const queries = queryCache.findAll({ queryKey: ['posts'] })
359 * ```
360 *
361 * @param filters - The filters to match. Without filters, every query is
362 * returned.
363 * @returns The matching queries.
364 * @see {@link QueryCache#find}
365 */
366 findAll(filters: QueryFilters<any> = {}): Array<Query> {
367 const queries = this.getAll()
368 return Object.keys(filters).length > 0
369 ? queries.filter((query) => matchQuery(filters, query))
370 : queries
371 }
372β
373 /**
374 * Notifies every cache listener of an event, in one batch.
375 *
376 * @param event - The event passed to every listener.
377 * @internal
378 */
379 notify(event: QueryCacheNotifyEvent): void {
380 notifyManager.batch(() => {
381 this.listeners.forEach((listener) => {
382 listener(event)
383 })
384 })
385 }
386β
387 /**
388 * Calls {@link Query#onFocus} on every cached query, in one batch.
389 *
390 * @internal
391 */
392 onFocus(): void {
393 notifyManager.batch(() => {
394 this.getAll().forEach((query) => {
395 query.onFocus()
396 })
397 })
398 }
399β
400 /**
401 * Calls {@link Query#onOnline} on every cached query, in one batch.
402 *
403 * @internal
404 */
405 onOnline(): void {
406 notifyManager.batch(() => {
407 this.getAll().forEach((query) => {
408 query.onOnline()
409 })
410 })
411 }
412}