Open History to see the last commit
1import { timeoutManager } from './timeoutManager'
2import type { Mutation } from './mutation'
3import type { FetchOptions, Query } from './query'
4import type {
5 DefaultError,
6 FetchStatus,
7 MutationKey,
8 MutationStatus,
9 QueryFunction,
10 QueryKey,
11 QueryOptions,
12} from './types'
13β
14// TYPES
15β
16type DropLast<T extends ReadonlyArray<unknown>> = T extends readonly [
17 ...infer R,
18 unknown,
19]
20 ? readonly [...R]
21 : never
22β
23type TuplePrefixes<T extends ReadonlyArray<unknown>> = T extends readonly []
24 ? readonly []
25 : TuplePrefixes<DropLast<T>> | T
26β
27/**
28 * Filters used to select queries, for example in `queryClient.getQueriesData` or `queryClient.invalidateQueries`.
29 * All provided filters must match; filters that are left unspecified are ignored.
30 */
31export interface QueryFilters<TQueryKey extends QueryKey = QueryKey> {
32 /**
33 * Filter to active queries, inactive queries or all queries
34 * @defaultValue 'all'
35 */
36 type?: QueryTypeFilter
37 /**
38 * Match query key exactly
39 */
40 exact?: boolean
41 /**
42 * Include queries matching this predicate function
43 */
44 predicate?: (query: Query) => boolean
45 /**
46 * Include queries matching this query key
47 */
48 queryKey?: TQueryKey | TuplePrefixes<TQueryKey>
49 /**
50 * Include or exclude stale queries
51 */
52 stale?: boolean
53 /**
54 * Include queries matching their fetchStatus
55 */
56 fetchStatus?: FetchStatus
57}
58β
59/**
60 * Filters used to select mutations, for example in `mutationCache.findAll` or `queryClient.isMutating`.
61 * All provided filters must match; filters that are left unspecified are ignored.
62 */
63export interface MutationFilters<
64 TData = unknown,
65 TError = DefaultError,
66 TVariables = unknown,
67 TOnMutateResult = unknown,
68> {
69 /**
70 * Match mutation key exactly
71 */
72 exact?: boolean
73 /**
74 * Include mutations matching this predicate function
75 */
76 predicate?: (
77 mutation: Mutation<TData, TError, TVariables, TOnMutateResult>,
78 ) => boolean
79 /**
80 * Include mutations matching this mutation key
81 */
82 mutationKey?: TuplePrefixes<MutationKey>
83 /**
84 * Filter by mutation status
85 */
86 status?: MutationStatus
87}
88β
89/**
90 * Either a plain value of type `TOutput`, or a function that receives `TInput` and returns `TOutput`.
91 * Used for example by `setQueryData`-style updaters, which accept either the new data directly or a
92 * function that computes it from the previous data. See {@link functionalUpdate}.
93 * @example
94 * ```ts
95 * queryClient.setQueryData(['posts'], newPosts)
96 *
97 * // Or, using an updater function that receives the current data:
98 * queryClient.setQueryData(['posts'], (oldPosts) =>
99 * oldPosts ? [...oldPosts, newPost] : oldPosts,
100 * )
101 * ```
102 */
103export type Updater<TInput, TOutput> = TOutput | ((input: TInput) => TOutput)
104β
105/**
106 * Which queries a filter matches: all of them, only active ones (with enabled observers), or only
107 * inactive ones.
108 */
109export type QueryTypeFilter = 'all' | 'active' | 'inactive'
110β
111// UTILS
112β
113/**
114 * @deprecated use `environmentManager.isServer()` instead.
115 */
116export const isServer = typeof window === 'undefined' || 'Deno' in globalThis
117β
118/**
119 * A function that does nothing.
120 */
121export function noop(): void
122export function noop(): undefined
123export function noop() {}
124β
125/**
126 * Resolves an {@link Updater}: calls it with `input` if it is a function, otherwise returns it as
127 * is.
128 * @param updater - The new value, or a function that receives `input` and returns the new value.
129 * @param input - The current value, passed to `updater` if it is a function.
130 * @returns The new value.
131 */
132export function functionalUpdate<TInput, TOutput>(
133 updater: Updater<TInput, TOutput>,
134 input: TInput,
135): TOutput {
136 return typeof updater === 'function'
137 ? (updater as (_: TInput) => TOutput)(input)
138 : updater
139}
140β
141/**
142 * Checks whether a value can be used as a timeout: a non-negative, finite number.
143 * @param value - The value to check.
144 * @returns `true` if `value` is a number that is `>= 0` and not `Infinity`.
145 */
146export function isValidTimeout(value: unknown): value is number {
147 return typeof value === 'number' && value >= 0 && value !== Infinity
148}
149β
150/**
151 * Calculates how long until data updated at `updatedAt` becomes stale.
152 * @param updatedAt - The timestamp, in milliseconds, at which the data was last updated.
153 * @param staleTime - The time, in milliseconds, after which data is considered stale. Defaults to
154 * `0`.
155 * @returns The remaining time in milliseconds, or `0` if the data is already stale.
156 */
157export function timeUntilStale(updatedAt: number, staleTime?: number): number {
158 return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0)
159}
160β
161/**
162 * Resolves an option that can be given either as a value or as a function of the query, such as
163 * `staleTime`.
164 * @param value - The option value, or a function that receives `query` and returns the value.
165 * @param query - The query passed to `value` if it is a function.
166 * @returns The resolved value, or `undefined` if `value` is `undefined`.
167 */
168export function resolveQueryValue<
169 TValue,
170 TQueryFnData = unknown,
171 TError = DefaultError,
172 TData = TQueryFnData,
173 TQueryKey extends QueryKey = QueryKey,
174>(
175 value:
176 | undefined
177 | TValue
178 | ((query: Query<TQueryFnData, TError, TData, TQueryKey>) => TValue),
179 query: Query<TQueryFnData, TError, TData, TQueryKey>,
180): TValue | undefined {
181 return typeof value === 'function'
182 ? (
183 value as (
184 query: Query<TQueryFnData, TError, TData, TQueryKey>,
185 ) => TValue
186 )(query)
187 : value
188}
189β
190/**
191 * Checks whether a query matches the given {@link QueryFilters}.
192 * Every filter that is specified must match; filters that are left unspecified are ignored.
193 * @param filters - The filters to check the query against.
194 * @param query - The query to check.
195 * @returns `true` if the query matches every specified filter.
196 * @example
197 * ```ts
198 * const queryCache = queryClient.getQueryCache()
199 *
200 * const matchingQueries = queryCache
201 * .getAll()
202 * .filter((query) => matchQuery({ queryKey: ['posts'] }, query))
203 * ```
204 */
205export function matchQuery(
206 filters: QueryFilters,
207 query: Query<any, any, any, any>,
208): boolean {
209 const {
210 type = 'all',
211 exact,
212 fetchStatus,
213 predicate,
214 queryKey,
215 stale,
216 } = filters
217β
218 if (queryKey) {
219 if (exact) {
220 if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {
221 return false
222 }
223 } else if (!partialMatchKey(query.queryKey, queryKey)) {
224 return false
225 }
226 }
227β
228 if (type !== 'all') {
229 const isActive = query.isActive()
230 if (type === 'active' && !isActive) {
231 return false
232 }
233 if (type === 'inactive' && isActive) {
234 return false
235 }
236 }
237β
238 if (typeof stale === 'boolean' && query.isStale() !== stale) {
239 return false
240 }
241β
242 if (fetchStatus && fetchStatus !== query.state.fetchStatus) {
243 return false
244 }
245β
246 if (predicate && !predicate(query)) {
247 return false
248 }
249β
250 return true
251}
252β
253/**
254 * Checks whether a mutation matches the given {@link MutationFilters}.
255 * Every filter that is specified must match; filters that are left unspecified are ignored.
256 * If a `mutationKey` filter is provided but the mutation has no `mutationKey` of its own, it does not match.
257 * @param filters - The filters to check the mutation against.
258 * @param mutation - The mutation to check.
259 * @returns `true` if the mutation matches every specified filter.
260 * @example
261 * ```ts
262 * const mutationCache = queryClient.getMutationCache()
263 *
264 * const matchingMutations = mutationCache
265 * .getAll()
266 * .filter((mutation) => matchMutation({ mutationKey: ['addPost'] }, mutation))
267 * ```
268 */
269export function matchMutation(
270 filters: MutationFilters,
271 mutation: Mutation<any, any>,
272): boolean {
273 const { exact, status, predicate, mutationKey } = filters
274 if (mutationKey) {
275 if (!mutation.options.mutationKey) {
276 return false
277 }
278 if (exact) {
279 if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) {
280 return false
281 }
282 } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {
283 return false
284 }
285 }
286β
287 if (status && mutation.state.status !== status) {
288 return false
289 }
290β
291 if (predicate && !predicate(mutation)) {
292 return false
293 }
294β
295 return true
296}
297β
298/**
299 * Hashes a query key with the query's `queryKeyHashFn` option, falling back to {@link hashKey}.
300 * @param queryKey - The query key to hash.
301 * @param options - The query options that may provide a custom `queryKeyHashFn`.
302 * @returns The query hash, a string that identifies the query in the cache.
303 */
304export function hashQueryKeyByOptions<TQueryKey extends QueryKey = QueryKey>(
305 queryKey: TQueryKey,
306 options?: Pick<QueryOptions<any, any, any, any>, 'queryKeyHashFn'>,
307): string {
308 const hashFn = options?.queryKeyHashFn || hashKey
309 return hashFn(queryKey)
310}
311β
312/**
313 * Default query & mutation keys hash function.
314 * Hashes the value into a stable hash.
315 * @param queryKey - The query or mutation key to hash.
316 * @returns The stable hash of the key, as a JSON string.
317 * @example
318 * ```ts
319 * // Object keys are sorted, so key order doesn't affect the hash:
320 * hashKey(['todos', { page: 1, filter: 'done' }]) // === '["todos",{"filter":"done","page":1}]'
321 * ```
322 */
323export function hashKey(queryKey: QueryKey | MutationKey): string {
324 return JSON.stringify(queryKey, (_, val) =>
325 isPlainObject(val)
326 ? Object.keys(val)
327 .sort()
328 .reduce((result, key) => {
329 result[key] = val[key]
330 return result
331 }, {} as any)
332 : val,
333 )
334}
335β
336/**
337 * Checks if key `b` partially matches with key `a`.
338 * @param a - The key to check, e.g. a query's own key.
339 * @param b - The (partial) key to match against `a`.
340 * @returns `true` if every array element or object property in `b` matches the one at the same
341 * position in `a`.
342 */
343export function partialMatchKey(a: QueryKey, b: QueryKey): boolean
344export function partialMatchKey(a: any, b: any): boolean {
345 if (a === b) {
346 return true
347 }
348β
349 if (typeof a !== typeof b) {
350 return false
351 }
352β
353 if (a && b && typeof a === 'object' && typeof b === 'object') {
354 if (Array.isArray(a) !== Array.isArray(b)) {
355 return false
356 }
357β
358 if (Array.isArray(a) && Array.isArray(b)) {
359 if (b.length > a.length) return false
360 for (let i = 0; i < b.length; i++) {
361 if (!partialMatchKey(a[i], b[i])) {
362 return false
363 }
364 }
365 return true
366 }
367β
368 const bKeys = Object.keys(b)
369 for (const key of bKeys) {
370 if (!partialMatchKey(a[key], b[key])) {
371 return false
372 }
373 }
374 return true
375 }
376β
377 return false
378}
379β
380const hasOwn = Object.prototype.hasOwnProperty
381β
382/**
383 * This function returns `a` if `b` is deeply equal.
384 * If not, it will replace any deeply equal children of `b` with those of `a`.
385 * This can be used for structural sharing between JSON values for example.
386 * @param a - The previous value, whose deeply equal parts are reused.
387 * @param b - The new value.
388 * @param depth - The current recursion depth. Past a depth of `500`, `b` is returned as is.
389 * @returns `a` if `b` is deeply equal to it, otherwise `b` with its deeply equal parts replaced by
390 * those of `a`.
391 */
392export function replaceEqualDeep<T>(a: unknown, b: T, depth?: number): T
393export function replaceEqualDeep(a: any, b: any, depth = 0): any {
394 if (a === b) {
395 return a
396 }
397β
398 if (depth > 500) return b
399β
400 const array = isPlainArray(a) && isPlainArray(b)
401β
402 if (!array && !(isPlainObject(a) && isPlainObject(b))) return b
403β
404 const aItems = array ? a : Object.keys(a)
405 const aSize = aItems.length
406 const bItems = array ? b : Object.keys(b)
407 const bSize = bItems.length
408 const copy: any = array ? new Array(bSize) : {}
409β
410 let equalItems = 0
411β
412 for (let i = 0; i < bSize; i++) {
413 const key: any = array ? i : bItems[i]
414 const aItem = a[key]
415 const bItem = b[key]
416β
417 if (aItem === bItem) {
418 copy[key] = aItem
419 if (array ? i < aSize : hasOwn.call(a, key)) equalItems++
420 continue
421 }
422β
423 if (
424 aItem === null ||
425 bItem === null ||
426 typeof aItem !== 'object' ||
427 typeof bItem !== 'object'
428 ) {
429 copy[key] = bItem
430 continue
431 }
432β
433 const v = replaceEqualDeep(aItem, bItem, depth + 1)
434 copy[key] = v
435 if (v === aItem) equalItems++
436 }
437β
438 return aSize === bSize && equalItems === aSize ? a : copy
439}
440β
441/**
442 * Shallow compare objects.
443 * @param a - The first object.
444 * @param b - The second object, or `undefined`.
445 * @returns `true` if both objects have the same keys, with strictly equal values for each key.
446 */
447export function shallowEqualObjects<T extends Record<string, any>>(
448 a: T,
449 b: T | undefined,
450): boolean {
451 if (!b || Object.keys(a).length !== Object.keys(b).length) {
452 return false
453 }
454β
455 for (const key of Object.keys(a)) {
456 if (!hasOwn.call(b, key) || a[key] !== b[key]) {
457 return false
458 }
459 }
460β
461 return true
462}
463β
464/**
465 * Checks whether a value is an array with no holes and no extra properties.
466 * @param value - The value to check.
467 * @returns `true` if `value` is an array whose number of own keys equals its `length`.
468 */
469export function isPlainArray(value: unknown): value is Array<unknown> {
470 return Array.isArray(value) && value.length === Object.keys(value).length
471}
472β
473// Copied from: https://github.com/jonschlinkert/is-plain-object
474/**
475 * Checks whether a value is a plain object, e.g. created with an object literal or
476 * `Object.create(null)`.
477 * @param o - The value to check.
478 * @returns `true` if `o` is a plain object.
479 */
480export function isPlainObject(o: any): o is Record<PropertyKey, unknown> {
481 if (!hasObjectPrototype(o)) {
482 return false
483 }
484β
485 // If has no constructor
486 const objectPrototype = Object.getPrototypeOf(o)
487 const ctor = objectPrototype?.constructor
488 if (ctor === undefined) {
489 return true
490 }
491β
492 if (typeof ctor !== 'function') {
493 return false
494 }
495β
496 // If has modified prototype
497 const prot = ctor.prototype
498 if (!hasObjectPrototype(prot)) {
499 return false
500 }
501β
502 // If constructor does not have an Object-specific method
503 if (!prot.hasOwnProperty('isPrototypeOf')) {
504 return false
505 }
506β
507 // Handles Objects created by Object.create(<arbitrary prototype>)
508 if (objectPrototype !== Object.prototype) {
509 return false
510 }
511β
512 // Most likely a plain Object
513 return true
514}
515β
516/**
517 * Checks whether a value's `Object.prototype.toString` tag is `[object Object]`.
518 * @param o - The value to check.
519 * @returns `true` if the tag is `[object Object]`.
520 */
521function hasObjectPrototype(o: any): boolean {
522 return Object.prototype.toString.call(o) === '[object Object]'
523}
524β
525/**
526 * Waits for the given time, using the configured {@link timeoutManager}.
527 * @param timeout - The time to wait, in milliseconds.
528 * @returns A promise that resolves after `timeout` milliseconds.
529 */
530export function sleep(timeout: number): Promise<void> {
531 return new Promise((resolve) => {
532 timeoutManager.setTimeout(resolve, timeout)
533 })
534}
535β
536/**
537 * Applies a query's `structuralSharing` option when writing new data.
538 * @param prevData - The previously cached data.
539 * @param data - The new data.
540 * @param options - The query options, whose `structuralSharing` decides how the data is merged.
541 * @returns The result of a custom `structuralSharing` function, `data` with its unchanged parts
542 * replaced by those of `prevData` by default, or `data` as is if `structuralSharing` is `false`.
543 * @throws {Error} The error from the default structural sharing, e.g. when the data is not JSON serializable.
544 * Outside production, it is also logged to the console.
545 */
546export function replaceData<
547 TData,
548 TOptions extends QueryOptions<any, any, any, any>,
549>(prevData: TData | undefined, data: TData, options: TOptions): TData {
550 if (typeof options.structuralSharing === 'function') {
551 return options.structuralSharing(prevData, data) as TData
552 } else if (options.structuralSharing !== false) {
553 if (process.env.NODE_ENV !== 'production') {
554 try {
555 return replaceEqualDeep(prevData, data)
556 } catch (error) {
557 console.error(
558 `Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${options.queryHash}]: ${error}`,
559 )
560β
561 // Prevent the replaceEqualDeep from being called again down below.
562 throw error
563 }
564 }
565 // Structurally share data between prev and new data if needed
566 return replaceEqualDeep(prevData, data)
567 }
568 return data
569}
570β
571/**
572 * Intended to be passed as a query's `placeholderData` option, for example
573 * `placeholderData: keepPreviousData`. Instead of resetting the query's data to `undefined` while a new
574 * query key is fetching, it keeps displaying the previously fetched data until the new data arrives.
575 * @param previousData - The data of the previous query key, passed by the observer.
576 * @returns The previous data, unchanged.
577 * @example
578 * ```ts
579 * new QueryObserver(queryClient, {
580 * queryKey: ['posts', page],
581 * queryFn: () => fetchPosts(page),
582 * placeholderData: keepPreviousData,
583 * })
584 * ```
585 */
586export function keepPreviousData<T>(
587 previousData: T | undefined,
588): T | undefined {
589 return previousData
590}
591β
592/**
593 * Adds an item to one end of a new array. If the result exceeds `max`, removes
594 * excess items from the opposite end.
595 * @param items - The current items.
596 * @param item - The value to add.
597 * @param max - The maximum number of items to keep. Omit it or use `0` for no limit.
598 * @param prepend - Pass `true` to add at the start. The default is to add at the end.
599 * @returns A new array with `item` added.
600 */
601export function addToArray<T>(
602 items: Array<T>,
603 item: T,
604 max?: number,
605 prepend?: boolean,
606): Array<T> {
607 const newItems = prepend ? [item, ...items] : [...items, item]
608 if (max && newItems.length > max) {
609 return prepend ? newItems.slice(0, max) : newItems.slice(-max)
610 }
611 return newItems
612}
613β
614/**
615 * Sentinel value that can be passed as a query's `queryFn` to conditionally disable the query (equivalent
616 * to `enabled: false`) while preserving full type inference for the query's data. Unlike `enabled: false`,
617 * a query disabled via `skipToken` cannot be triggered with `refetch`.
618 * @example
619 * ```ts
620 * new QueryObserver(queryClient, {
621 * queryKey: ['post', postId],
622 * queryFn: postId != null ? () => fetchPost(postId) : skipToken,
623 * })
624 * ```
625 */
626export const skipToken = Symbol()
627/**
628 * The type of the {@link skipToken} sentinel value.
629 */
630export type SkipToken = typeof skipToken
631β
632/**
633 * Returns the function to call for a fetch. If there is no `queryFn` but the fetch was started from
634 * an `initialPromise`, that promise is returned instead. If there is no usable `queryFn` (missing or
635 * {@link skipToken}), the returned function rejects with a `Missing queryFn` error.
636 * @param options - The query options with the `queryFn`, and the `queryHash` used in error messages.
637 * @param fetchOptions - The fetch options, which may carry an `initialPromise`.
638 * @returns The function to call for the fetch.
639 */
640export function ensureQueryFn<
641 TQueryFnData = unknown,
642 TQueryKey extends QueryKey = QueryKey,
643>(
644 options: {
645 queryFn?: QueryFunction<TQueryFnData, TQueryKey> | SkipToken
646 queryHash?: string
647 },
648 fetchOptions?: FetchOptions<TQueryFnData>,
649): QueryFunction<TQueryFnData, TQueryKey> {
650 if (process.env.NODE_ENV !== 'production') {
651 if (options.queryFn === skipToken) {
652 console.error(
653 `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`,
654 )
655 }
656 }
657β
658 // if we attempt to retry a fetch that was triggered from an initialPromise
659 // when we don't have a queryFn yet, we can't retry, so we just return the already rejected initialPromise
660 // if an observer has already mounted, we will be able to retry with that queryFn
661 if (!options.queryFn && fetchOptions?.initialPromise) {
662 return () => fetchOptions.initialPromise!
663 }
664β
665 if (!options.queryFn || options.queryFn === skipToken) {
666 return () =>
667 Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`))
668 }
669β
670 return options.queryFn
671}
672β
673/**
674 * Resolves a `throwOnError` option to a boolean.
675 * If `throwOnError` is a function, it is called with `params` (e.g. the error and, depending on the caller,
676 * additional context such as the query or mutation) and its result is returned, allowing the throwing
677 * behavior to be decided per error. Otherwise, `throwOnError` itself is coerced to a boolean (`undefined`
678 * resolves to `false`).
679 * @param throwOnError - The `throwOnError` option: a boolean, a function that decides per error, or
680 * `undefined`.
681 * @param params - The arguments passed to `throwOnError` if it is a function.
682 * @returns Whether the error should be thrown.
683 * @example
684 * ```ts
685 * const throwOnError =
686 * query.state.error && typeof options.throwOnError === 'function'
687 * ? shouldThrowError(options.throwOnError, [query.state.error, query])
688 * : options.throwOnError
689 * ```
690 */
691export function shouldThrowError<T extends (...args: Array<any>) => boolean>(
692 throwOnError: boolean | T | undefined,
693 params: Parameters<T>,
694): boolean {
695 // Allow throwOnError function to override throwing behavior on a per-error basis
696 if (typeof throwOnError === 'function') {
697 return throwOnError(...params)
698 }
699β
700 return !!throwOnError
701}
702β
703export const fetchSignal = Symbol()
704β
705/** Internal view of a context that can expose its signal without consuming it. */
706export type FetchSignalContext = {
707 /** The public signal, whose getter can mark it consumed. */
708 readonly signal: AbortSignal
709 /** The original fetch signal, absent on application-created contexts. */
710 readonly [fetchSignal]?: AbortSignal
711}
712β
713/**
714 * Adds a lazy `signal` getter to an object, such as a query function context. The first time
715 * `signal` is read, `onCancelled` is registered for the signal's `abort` event (or called right
716 * away if it is already aborted), so cancellation is only tracked when the signal is actually used.
717 * @param object - The object to add the `signal` property to.
718 * @param getSignal - Returns the `AbortSignal`. Called once, when `signal` is first read.
719 * @param onCancelled - Called when the signal is aborted, if `signal` was read.
720 * @param internalSignal - The fetch signal to forward without consuming the getter.
721 * @returns The same object, with the `signal` property added.
722 */
723export function addConsumeAwareSignal<T extends object>(
724 object: T,
725 getSignal: () => AbortSignal,
726 onCancelled: () => void,
727 internalSignal?: AbortSignal,
728): T & { signal: AbortSignal } {
729 let consumed = false
730 let signal: AbortSignal | undefined
731β
732 Object.defineProperties(object, {
733 [fetchSignal]: { value: internalSignal },
734 signal: {
735 enumerable: true,
736 get: () => {
737 signal ??= getSignal()
738 if (consumed) {
739 return signal
740 }
741β
742 consumed = true
743 if (signal.aborted) {
744 onCancelled()
745 } else {
746 signal.addEventListener('abort', onCancelled, { once: true })
747 }
748β
749 return signal
750 },
751 },
752 })
753β
754 return object as T & { signal: AbortSignal }
755}