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