Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

queryCache.ts

353 lines10.4 KB

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