From 9859ff34b3af7afd3dccf4a5bb69e7302fe7ab10 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Thu, 5 Jan 2023 20:33:22 +0100 Subject: [PATCH 01/60] refactor: updated supported browsers to get smaller bundlesize --- .browserslistrc | 12 ++++++------ babel.config.js | 1 + 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/.browserslistrc b/.browserslistrc index 01b924286ad..980cd0a0270 100644 --- a/.browserslistrc +++ b/.browserslistrc @@ -1,7 +1,7 @@ # Browsers we support -Chrome >= 73 -Firefox >= 78 -Edge >= 79 -Safari >= 12.0 -iOS >= 12.0 -opera >= 53 +Chrome >= 84 +Firefox >= 90 +Edge >= 84 +Safari >= 15 +iOS >= 15 +opera >= 70 diff --git a/babel.config.js b/babel.config.js index dc23100fd42..05a15ce4c09 100644 --- a/babel.config.js +++ b/babel.config.js @@ -9,6 +9,7 @@ module.exports = { '@babel/preset-env', { loose, + bugfixes: true, modules: false, exclude: [ '@babel/plugin-transform-regenerator', From 55e33947601529bf73d8d2032eaca90896df9738 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Thu, 5 Jan 2023 21:14:06 +0100 Subject: [PATCH 02/60] refactor: switch to private fields and methods --- packages/query-core/src/focusManager.ts | 28 +-- packages/query-core/src/mutation.ts | 68 +++--- packages/query-core/src/mutationCache.ts | 26 +- packages/query-core/src/mutationObserver.ts | 106 ++++----- packages/query-core/src/onlineManager.ts | 28 +-- packages/query-core/src/queriesObserver.ts | 76 +++--- packages/query-core/src/query.ts | 130 +++++----- packages/query-core/src/queryCache.ts | 36 +-- packages/query-core/src/queryClient.ts | 122 +++++----- packages/query-core/src/queryObserver.ts | 250 ++++++++++---------- packages/query-core/src/removable.ts | 10 +- 11 files changed, 443 insertions(+), 437 deletions(-) diff --git a/packages/query-core/src/focusManager.ts b/packages/query-core/src/focusManager.ts index 5397c6a6c62..ac310f5947f 100644 --- a/packages/query-core/src/focusManager.ts +++ b/packages/query-core/src/focusManager.ts @@ -6,14 +6,14 @@ type SetupFn = ( ) => (() => void) | undefined export class FocusManager extends Subscribable { - private focused?: boolean - private cleanup?: () => void + #focused?: boolean + #cleanup?: () => void - private setup: SetupFn + #setup: SetupFn constructor() { super() - this.setup = (onFocus) => { + this.#setup = (onFocus) => { // addEventListener does not exist in React Native, but window does // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!isServer && window.addEventListener) { @@ -33,22 +33,22 @@ export class FocusManager extends Subscribable { } protected onSubscribe(): void { - if (!this.cleanup) { - this.setEventListener(this.setup) + if (!this.#cleanup) { + this.setEventListener(this.#setup) } } protected onUnsubscribe() { if (!this.hasListeners()) { - this.cleanup?.() - this.cleanup = undefined + this.#cleanup?.() + this.#cleanup = undefined } } setEventListener(setup: SetupFn): void { - this.setup = setup - this.cleanup?.() - this.cleanup = setup((focused) => { + this.#setup = setup + this.#cleanup?.() + this.#cleanup = setup((focused) => { if (typeof focused === 'boolean') { this.setFocused(focused) } else { @@ -58,7 +58,7 @@ export class FocusManager extends Subscribable { } setFocused(focused?: boolean): void { - this.focused = focused + this.#focused = focused if (focused) { this.onFocus() @@ -72,8 +72,8 @@ export class FocusManager extends Subscribable { } isFocused(): boolean { - if (typeof this.focused === 'boolean') { - return this.focused + if (typeof this.#focused === 'boolean') { + return this.#focused } // document global can be unavailable in react native diff --git a/packages/query-core/src/mutation.ts b/packages/query-core/src/mutation.ts index 7d3ee1bfb88..b25793153e0 100644 --- a/packages/query-core/src/mutation.ts +++ b/packages/query-core/src/mutation.ts @@ -92,10 +92,10 @@ export class Mutation< options: MutationOptions mutationId: number - private observers: MutationObserver[] - private mutationCache: MutationCache - private logger: Logger - private retryer?: Retryer + #observers: MutationObserver[] + #mutationCache: MutationCache + #logger: Logger + #retryer?: Retryer constructor(config: MutationConfig) { super() @@ -105,9 +105,9 @@ export class Mutation< ...config.options, } this.mutationId = config.mutationId - this.mutationCache = config.mutationCache - this.logger = config.logger || defaultLogger - this.observers = [] + this.#mutationCache = config.mutationCache + this.#logger = config.logger || defaultLogger + this.#observers = [] this.state = config.state || getDefaultState() this.updateCacheTime(this.options.cacheTime) @@ -119,17 +119,17 @@ export class Mutation< } setState(state: MutationState): void { - this.dispatch({ type: 'setState', state }) + this.#dispatch({ type: 'setState', state }) } addObserver(observer: MutationObserver): void { - if (this.observers.indexOf(observer) === -1) { - this.observers.push(observer) + if (this.#observers.indexOf(observer) === -1) { + this.#observers.push(observer) // Stop the mutation from being garbage collected this.clearGcTimeout() - this.mutationCache.notify({ + this.#mutationCache.notify({ type: 'observerAdded', mutation: this, observer, @@ -138,11 +138,11 @@ export class Mutation< } removeObserver(observer: MutationObserver): void { - this.observers = this.observers.filter((x) => x !== observer) + this.#observers = this.#observers.filter((x) => x !== observer) this.scheduleGc() - this.mutationCache.notify({ + this.#mutationCache.notify({ type: 'observerRemoved', mutation: this, observer, @@ -150,26 +150,26 @@ export class Mutation< } protected optionalRemove() { - if (!this.observers.length) { + if (!this.#observers.length) { if (this.state.status === 'loading') { this.scheduleGc() } else { - this.mutationCache.remove(this) + this.#mutationCache.remove(this) } } } continue(): Promise { - if (this.retryer) { - this.retryer.continue() - return this.retryer.promise + if (this.#retryer) { + this.#retryer.continue() + return this.#retryer.promise } return this.execute() } async execute(): Promise { const executeMutation = () => { - this.retryer = createRetryer({ + this.#retryer = createRetryer({ fn: () => { if (!this.options.mutationFn) { return Promise.reject('No mutationFn found') @@ -177,34 +177,34 @@ export class Mutation< return this.options.mutationFn(this.state.variables!) }, onFail: (failureCount, error) => { - this.dispatch({ type: 'failed', failureCount, error }) + this.#dispatch({ type: 'failed', failureCount, error }) }, onPause: () => { - this.dispatch({ type: 'pause' }) + this.#dispatch({ type: 'pause' }) }, onContinue: () => { - this.dispatch({ type: 'continue' }) + this.#dispatch({ type: 'continue' }) }, retry: this.options.retry ?? 0, retryDelay: this.options.retryDelay, networkMode: this.options.networkMode, }) - return this.retryer.promise + return this.#retryer.promise } const restored = this.state.status === 'loading' try { if (!restored) { - this.dispatch({ type: 'loading', variables: this.options.variables! }) + this.#dispatch({ type: 'loading', variables: this.options.variables! }) // Notify cache callback - await this.mutationCache.config.onMutate?.( + await this.#mutationCache.config.onMutate?.( this.state.variables, this as Mutation, ) const context = await this.options.onMutate?.(this.state.variables!) if (context !== this.state.context) { - this.dispatch({ + this.#dispatch({ type: 'loading', context, variables: this.state.variables, @@ -214,7 +214,7 @@ export class Mutation< const data = await executeMutation() // Notify cache callback - await this.mutationCache.config.onSuccess?.( + await this.#mutationCache.config.onSuccess?.( data, this.state.variables, this.state.context, @@ -234,12 +234,12 @@ export class Mutation< this.state.context, ) - this.dispatch({ type: 'success', data }) + this.#dispatch({ type: 'success', data }) return data } catch (error) { try { // Notify cache callback - await this.mutationCache.config.onError?.( + await this.#mutationCache.config.onError?.( error, this.state.variables, this.state.context, @@ -247,7 +247,7 @@ export class Mutation< ) if (process.env.NODE_ENV !== 'production') { - this.logger.error(error) + this.#logger.error(error) } await this.options.onError?.( @@ -264,12 +264,12 @@ export class Mutation< ) throw error } finally { - this.dispatch({ type: 'error', error: error as TError }) + this.#dispatch({ type: 'error', error: error as TError }) } } } - private dispatch(action: Action): void { + #dispatch(action: Action): void { const reducer = ( state: MutationState, ): MutationState => { @@ -332,10 +332,10 @@ export class Mutation< this.state = reducer(this.state) notifyManager.batch(() => { - this.observers.forEach((observer) => { + this.#observers.forEach((observer) => { observer.onMutationUpdate(action) }) - this.mutationCache.notify({ + this.#mutationCache.notify({ mutation: this, type: 'updated', action, diff --git a/packages/query-core/src/mutationCache.ts b/packages/query-core/src/mutationCache.ts index acf87caf709..d8ea89ba31a 100644 --- a/packages/query-core/src/mutationCache.ts +++ b/packages/query-core/src/mutationCache.ts @@ -77,14 +77,14 @@ type MutationCacheListener = (event: MutationCacheNotifyEvent) => void export class MutationCache extends Subscribable { config: MutationCacheConfig - private mutations: Mutation[] - private mutationId: number + #mutations: Mutation[] + #mutationId: number constructor(config?: MutationCacheConfig) { super() this.config = config || {} - this.mutations = [] - this.mutationId = 0 + this.#mutations = [] + this.#mutationId = 0 } build( @@ -95,7 +95,7 @@ export class MutationCache extends Subscribable { const mutation = new Mutation({ mutationCache: this, logger: client.getLogger(), - mutationId: ++this.mutationId, + mutationId: ++this.#mutationId, options: client.defaultMutationOptions(options), state, defaultOptions: options.mutationKey @@ -109,25 +109,25 @@ export class MutationCache extends Subscribable { } add(mutation: Mutation): void { - this.mutations.push(mutation) + this.#mutations.push(mutation) this.notify({ type: 'added', mutation }) } remove(mutation: Mutation): void { - this.mutations = this.mutations.filter((x) => x !== mutation) + this.#mutations = this.#mutations.filter((x) => x !== mutation) this.notify({ type: 'removed', mutation }) } clear(): void { notifyManager.batch(() => { - this.mutations.forEach((mutation) => { + this.#mutations.forEach((mutation) => { this.remove(mutation) }) }) } getAll(): Mutation[] { - return this.mutations + return this.#mutations } find( @@ -137,11 +137,13 @@ export class MutationCache extends Subscribable { filters.exact = true } - return this.mutations.find((mutation) => matchMutation(filters, mutation)) + return this.#mutations.find((mutation) => matchMutation(filters, mutation)) } findAll(filters: MutationFilters): Mutation[] { - return this.mutations.filter((mutation) => matchMutation(filters, mutation)) + return this.#mutations.filter((mutation) => + matchMutation(filters, mutation), + ) } notify(event: MutationCacheNotifyEvent) { @@ -153,7 +155,7 @@ export class MutationCache extends Subscribable { } resumePausedMutations(): Promise { - const pausedMutations = this.mutations.filter((x) => x.state.isPaused) + const pausedMutations = this.#mutations.filter((x) => x.state.isPaused) return notifyManager.batch(() => pausedMutations.reduce( (promise, mutation) => diff --git a/packages/query-core/src/mutationObserver.ts b/packages/query-core/src/mutationObserver.ts index 20f7e62da2c..a3d140cc516 100644 --- a/packages/query-core/src/mutationObserver.ts +++ b/packages/query-core/src/mutationObserver.ts @@ -35,15 +35,11 @@ export class MutationObserver< > { options!: MutationObserverOptions - private client: QueryClient - private currentResult!: MutationObserverResult< - TData, - TError, - TVariables, - TContext - > - private currentMutation?: Mutation - private mutateOptions?: MutateOptions + #client: QueryClient + #currentResult: MutationObserverResult = + undefined! + #currentMutation?: Mutation + #mutateOptions?: MutateOptions constructor( client: QueryClient, @@ -51,10 +47,10 @@ export class MutationObserver< ) { super() - this.client = client + this.#client = client this.setOptions(options) this.bindMethods() - this.updateResult() + this.#updateResult() } protected bindMethods(): void { @@ -66,11 +62,11 @@ export class MutationObserver< options?: MutationObserverOptions, ) { const prevOptions = this.options - this.options = this.client.defaultMutationOptions(options) + this.options = this.#client.defaultMutationOptions(options) if (!shallowEqualObjects(prevOptions, this.options)) { - this.client.getMutationCache().notify({ + this.#client.getMutationCache().notify({ type: 'observerOptionsUpdated', - mutation: this.currentMutation, + mutation: this.#currentMutation, observer: this, }) } @@ -78,12 +74,12 @@ export class MutationObserver< protected onUnsubscribe(): void { if (!this.listeners.length) { - this.currentMutation?.removeObserver(this) + this.#currentMutation?.removeObserver(this) } } onMutationUpdate(action: Action): void { - this.updateResult() + this.#updateResult() // Determine which callbacks to trigger const notifyOptions: NotifyOptions = { @@ -96,7 +92,7 @@ export class MutationObserver< notifyOptions.onError = true } - this.notify(notifyOptions) + this.#notify(notifyOptions) } getCurrentResult(): MutationObserverResult< @@ -105,39 +101,41 @@ export class MutationObserver< TVariables, TContext > { - return this.currentResult + return this.#currentResult } reset(): void { - this.currentMutation = undefined - this.updateResult() - this.notify({ listeners: true }) + this.#currentMutation = undefined + this.#updateResult() + this.#notify({ listeners: true }) } mutate( variables?: TVariables, options?: MutateOptions, ): Promise { - this.mutateOptions = options + this.#mutateOptions = options - if (this.currentMutation) { - this.currentMutation.removeObserver(this) + if (this.#currentMutation) { + this.#currentMutation.removeObserver(this) } - this.currentMutation = this.client.getMutationCache().build(this.client, { - ...this.options, - variables: - typeof variables !== 'undefined' ? variables : this.options.variables, - }) + this.#currentMutation = this.#client + .getMutationCache() + .build(this.#client, { + ...this.options, + variables: + typeof variables !== 'undefined' ? variables : this.options.variables, + }) - this.currentMutation.addObserver(this) + this.#currentMutation.addObserver(this) - return this.currentMutation.execute() + return this.#currentMutation.execute() } - private updateResult(): void { - const state = this.currentMutation - ? this.currentMutation.state + #updateResult(): void { + const state = this.#currentMutation + ? this.#currentMutation.state : getDefaultState() const result: MutationObserverBaseResult< @@ -155,7 +153,7 @@ export class MutationObserver< reset: this.reset, } - this.currentResult = result as MutationObserverResult< + this.#currentResult = result as MutationObserverResult< TData, TError, TVariables, @@ -163,33 +161,33 @@ export class MutationObserver< > } - private notify(options: NotifyOptions) { + #notify(options: NotifyOptions) { notifyManager.batch(() => { // First trigger the mutate callbacks - if (this.mutateOptions) { + if (this.#mutateOptions) { if (options.onSuccess) { - this.mutateOptions.onSuccess?.( - this.currentResult.data!, - this.currentResult.variables!, - this.currentResult.context!, + this.#mutateOptions.onSuccess?.( + this.#currentResult.data!, + this.#currentResult.variables!, + this.#currentResult.context!, ) - this.mutateOptions.onSettled?.( - this.currentResult.data!, + this.#mutateOptions.onSettled?.( + this.#currentResult.data!, null, - this.currentResult.variables!, - this.currentResult.context, + this.#currentResult.variables!, + this.#currentResult.context, ) } else if (options.onError) { - this.mutateOptions.onError?.( - this.currentResult.error!, - this.currentResult.variables!, - this.currentResult.context, + this.#mutateOptions.onError?.( + this.#currentResult.error!, + this.#currentResult.variables!, + this.#currentResult.context, ) - this.mutateOptions.onSettled?.( + this.#mutateOptions.onSettled?.( undefined, - this.currentResult.error, - this.currentResult.variables!, - this.currentResult.context, + this.#currentResult.error, + this.#currentResult.variables!, + this.#currentResult.context, ) } } @@ -197,7 +195,7 @@ export class MutationObserver< // Then trigger the listeners if (options.listeners) { this.listeners.forEach((listener) => { - listener(this.currentResult) + listener(this.#currentResult) }) } }) diff --git a/packages/query-core/src/onlineManager.ts b/packages/query-core/src/onlineManager.ts index dd5c7ce1139..8d032d9fd87 100644 --- a/packages/query-core/src/onlineManager.ts +++ b/packages/query-core/src/onlineManager.ts @@ -6,14 +6,14 @@ type SetupFn = ( ) => (() => void) | undefined export class OnlineManager extends Subscribable { - private online?: boolean - private cleanup?: () => void + #online?: boolean + #cleanup?: () => void - private setup: SetupFn + #setup: SetupFn constructor() { super() - this.setup = (onOnline) => { + this.#setup = (onOnline) => { // addEventListener does not exist in React Native, but window does // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!isServer && window.addEventListener) { @@ -34,22 +34,22 @@ export class OnlineManager extends Subscribable { } protected onSubscribe(): void { - if (!this.cleanup) { - this.setEventListener(this.setup) + if (!this.#cleanup) { + this.setEventListener(this.#setup) } } protected onUnsubscribe() { if (!this.hasListeners()) { - this.cleanup?.() - this.cleanup = undefined + this.#cleanup?.() + this.#cleanup = undefined } } setEventListener(setup: SetupFn): void { - this.setup = setup - this.cleanup?.() - this.cleanup = setup((online?: boolean) => { + this.#setup = setup + this.#cleanup?.() + this.#cleanup = setup((online?: boolean) => { if (typeof online === 'boolean') { this.setOnline(online) } else { @@ -59,7 +59,7 @@ export class OnlineManager extends Subscribable { } setOnline(online?: boolean): void { - this.online = online + this.#online = online if (online) { this.onOnline() @@ -73,8 +73,8 @@ export class OnlineManager extends Subscribable { } isOnline(): boolean { - if (typeof this.online === 'boolean') { - return this.online + if (typeof this.#online === 'boolean') { + return this.#online } if ( diff --git a/packages/query-core/src/queriesObserver.ts b/packages/query-core/src/queriesObserver.ts index c9fbc5e164e..387d553ebe2 100644 --- a/packages/query-core/src/queriesObserver.ts +++ b/packages/query-core/src/queriesObserver.ts @@ -13,20 +13,20 @@ import { Subscribable } from './subscribable' type QueriesObserverListener = (result: QueryObserverResult[]) => void export class QueriesObserver extends Subscribable { - private client: QueryClient - private result: QueryObserverResult[] - private queries: QueryObserverOptions[] - private observers: QueryObserver[] - private observersMap: Record + #client: QueryClient + #result: QueryObserverResult[] + #queries: QueryObserverOptions[] + #observers: QueryObserver[] + #observersMap: Record constructor(client: QueryClient, queries?: QueryObserverOptions[]) { super() - this.client = client - this.queries = [] - this.result = [] - this.observers = [] - this.observersMap = {} + this.#client = client + this.#queries = [] + this.#result = [] + this.#observers = [] + this.#observersMap = {} if (queries) { this.setQueries(queries) @@ -35,9 +35,9 @@ export class QueriesObserver extends Subscribable { protected onSubscribe(): void { if (this.listeners.length === 1) { - this.observers.forEach((observer) => { + this.#observers.forEach((observer) => { observer.subscribe((result) => { - this.onUpdate(observer, result) + this.#onUpdate(observer, result) }) }) } @@ -51,7 +51,7 @@ export class QueriesObserver extends Subscribable { destroy(): void { this.listeners = [] - this.observers.forEach((observer) => { + this.#observers.forEach((observer) => { observer.destroy() }) } @@ -60,12 +60,12 @@ export class QueriesObserver extends Subscribable { queries: QueryObserverOptions[], notifyOptions?: NotifyOptions, ): void { - this.queries = queries + this.#queries = queries notifyManager.batch(() => { - const prevObservers = this.observers + const prevObservers = this.#observers - const newObserverMatches = this.findMatchingObservers(this.queries) + const newObserverMatches = this.#findMatchingObservers(this.#queries) // set options for the new observers to notify of changes newObserverMatches.forEach((match) => @@ -87,9 +87,9 @@ export class QueriesObserver extends Subscribable { return } - this.observers = newObservers - this.observersMap = newObserversMap - this.result = newResult + this.#observers = newObservers + this.#observersMap = newObserversMap + this.#result = newResult if (!this.hasListeners()) { return @@ -101,38 +101,38 @@ export class QueriesObserver extends Subscribable { difference(newObservers, prevObservers).forEach((observer) => { observer.subscribe((result) => { - this.onUpdate(observer, result) + this.#onUpdate(observer, result) }) }) - this.notify() + this.#notify() }) } getCurrentResult(): QueryObserverResult[] { - return this.result + return this.#result } getQueries() { - return this.observers.map((observer) => observer.getCurrentQuery()) + return this.#observers.map((observer) => observer.getCurrentQuery()) } getObservers() { - return this.observers + return this.#observers } getOptimisticResult(queries: QueryObserverOptions[]): QueryObserverResult[] { - return this.findMatchingObservers(queries).map((match) => + return this.#findMatchingObservers(queries).map((match) => match.observer.getOptimisticResult(match.defaultedQueryOptions), ) } - private findMatchingObservers( + #findMatchingObservers( queries: QueryObserverOptions[], ): QueryObserverMatch[] { - const prevObservers = this.observers + const prevObservers = this.#observers const defaultedQueryOptions = queries.map((options) => - this.client.defaultQueryOptions(options), + this.#client.defaultQueryOptions(options), ) const matchingObservers: QueryObserverMatch[] = @@ -161,9 +161,11 @@ export class QueriesObserver extends Subscribable { ) const getObserver = (options: QueryObserverOptions): QueryObserver => { - const defaultedOptions = this.client.defaultQueryOptions(options) - const currentObserver = this.observersMap[defaultedOptions.queryHash!] - return currentObserver ?? new QueryObserver(this.client, defaultedOptions) + const defaultedOptions = this.#client.defaultQueryOptions(options) + const currentObserver = this.#observersMap[defaultedOptions.queryHash!] + return ( + currentObserver ?? new QueryObserver(this.#client, defaultedOptions) + ) } const newOrReusedObservers: QueryObserverMatch[] = unmatchedQueries.map( @@ -197,18 +199,18 @@ export class QueriesObserver extends Subscribable { .sort(sortMatchesByOrderOfQueries) } - private onUpdate(observer: QueryObserver, result: QueryObserverResult): void { - const index = this.observers.indexOf(observer) + #onUpdate(observer: QueryObserver, result: QueryObserverResult): void { + const index = this.#observers.indexOf(observer) if (index !== -1) { - this.result = replaceAt(this.result, index, result) - this.notify() + this.#result = replaceAt(this.#result, index, result) + this.#notify() } } - private notify(): void { + #notify(): void { notifyManager.batch(() => { this.listeners.forEach((listener) => { - listener(this.result) + listener(this.#result) }) }) } diff --git a/packages/query-core/src/query.ts b/packages/query-core/src/query.ts index fbbbc4c628e..5649b73d08f 100644 --- a/packages/query-core/src/query.ts +++ b/packages/query-core/src/query.ts @@ -152,23 +152,23 @@ export class Query< state: QueryState isFetchingOptimistic?: boolean - private cache: QueryCache - private logger: Logger - private promise?: Promise - private retryer?: Retryer - private observers: QueryObserver[] - private defaultOptions?: QueryOptions - private abortSignalConsumed: boolean + #cache: QueryCache + #logger: Logger + #promise?: Promise + #retryer?: Retryer + #observers: QueryObserver[] + #defaultOptions?: QueryOptions + #abortSignalConsumed: boolean constructor(config: QueryConfig) { super() - this.abortSignalConsumed = false - this.defaultOptions = config.defaultOptions - this.setOptions(config.options) - this.observers = [] - this.cache = config.cache - this.logger = config.logger || defaultLogger + this.#abortSignalConsumed = false + this.#defaultOptions = config.defaultOptions + this.#setOptions(config.options) + this.#observers = [] + this.#cache = config.cache + this.#logger = config.logger || defaultLogger this.queryKey = config.queryKey this.queryHash = config.queryHash this.initialState = config.state || getDefaultState(this.options) @@ -179,17 +179,17 @@ export class Query< return this.options.meta } - private setOptions( + #setOptions( options?: QueryOptions, ): void { - this.options = { ...this.defaultOptions, ...options } + this.options = { ...this.#defaultOptions, ...options } this.updateCacheTime(this.options.cacheTime) } protected optionalRemove() { - if (!this.observers.length && this.state.fetchStatus === 'idle') { - this.cache.remove(this) + if (!this.#observers.length && this.state.fetchStatus === 'idle') { + this.#cache.remove(this) } } @@ -200,7 +200,7 @@ export class Query< const data = replaceData(this.state.data, newData, this.options) // Set data and mark it as cached - this.dispatch({ + this.#dispatch({ data, type: 'success', dataUpdatedAt: options?.updatedAt, @@ -214,12 +214,12 @@ export class Query< state: QueryState, setStateOptions?: SetStateOptions, ): void { - this.dispatch({ type: 'setState', state, setStateOptions }) + this.#dispatch({ type: 'setState', state, setStateOptions }) } cancel(options?: CancelOptions): Promise { - const promise = this.promise - this.retryer?.cancel(options) + const promise = this.#promise + this.#retryer?.cancel(options) return promise ? promise.then(noop).catch(noop) : Promise.resolve() } @@ -235,7 +235,9 @@ export class Query< } isActive(): boolean { - return this.observers.some((observer) => observer.options.enabled !== false) + return this.#observers.some( + (observer) => observer.options.enabled !== false, + ) } isDisabled(): boolean { @@ -246,7 +248,7 @@ export class Query< return ( this.state.isInvalidated || !this.state.dataUpdatedAt || - this.observers.some((observer) => observer.getCurrentResult().isStale) + this.#observers.some((observer) => observer.getCurrentResult().isStale) ) } @@ -259,67 +261,67 @@ export class Query< } onFocus(): void { - const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus()) + const observer = this.#observers.find((x) => x.shouldFetchOnWindowFocus()) if (observer) { observer.refetch({ cancelRefetch: false }) } // Continue fetch if currently paused - this.retryer?.continue() + this.#retryer?.continue() } onOnline(): void { - const observer = this.observers.find((x) => x.shouldFetchOnReconnect()) + const observer = this.#observers.find((x) => x.shouldFetchOnReconnect()) if (observer) { observer.refetch({ cancelRefetch: false }) } // Continue fetch if currently paused - this.retryer?.continue() + this.#retryer?.continue() } addObserver(observer: QueryObserver): void { - if (this.observers.indexOf(observer) === -1) { - this.observers.push(observer) + if (this.#observers.indexOf(observer) === -1) { + this.#observers.push(observer) // Stop the query from being garbage collected this.clearGcTimeout() - this.cache.notify({ type: 'observerAdded', query: this, observer }) + this.#cache.notify({ type: 'observerAdded', query: this, observer }) } } removeObserver(observer: QueryObserver): void { - if (this.observers.indexOf(observer) !== -1) { - this.observers = this.observers.filter((x) => x !== observer) + if (this.#observers.indexOf(observer) !== -1) { + this.#observers = this.#observers.filter((x) => x !== observer) - if (!this.observers.length) { + if (!this.#observers.length) { // If the transport layer does not support cancellation // we'll let the query continue so the result can be cached - if (this.retryer) { - if (this.abortSignalConsumed) { - this.retryer.cancel({ revert: true }) + if (this.#retryer) { + if (this.#abortSignalConsumed) { + this.#retryer.cancel({ revert: true }) } else { - this.retryer.cancelRetry() + this.#retryer.cancelRetry() } } this.scheduleGc() } - this.cache.notify({ type: 'observerRemoved', query: this, observer }) + this.#cache.notify({ type: 'observerRemoved', query: this, observer }) } } getObserversCount(): number { - return this.observers.length + return this.#observers.length } invalidate(): void { if (!this.state.isInvalidated) { - this.dispatch({ type: 'invalidate' }) + this.#dispatch({ type: 'invalidate' }) } } @@ -331,31 +333,31 @@ export class Query< if (this.state.dataUpdatedAt && fetchOptions?.cancelRefetch) { // Silently cancel current fetch if the user wants to cancel refetches this.cancel({ silent: true }) - } else if (this.promise) { + } else if (this.#promise) { // make sure that retries that were potentially cancelled due to unmounts can continue - this.retryer?.continueRetry() + this.#retryer?.continueRetry() // Return current promise if we are already fetching - return this.promise + return this.#promise } } // Update config if passed, otherwise the config from the last execution is used if (options) { - this.setOptions(options) + this.#setOptions(options) } // Use the options from the first observer with a query function if no function is found. // This can happen when the query is hydrated or created with setQueryData. if (!this.options.queryFn) { - const observer = this.observers.find((x) => x.options.queryFn) + const observer = this.#observers.find((x) => x.options.queryFn) if (observer) { - this.setOptions(observer.options) + this.#setOptions(observer.options) } } if (!Array.isArray(this.options.queryKey)) { if (process.env.NODE_ENV !== 'production') { - this.logger.error( + this.#logger.error( `As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`, ) } @@ -378,7 +380,7 @@ export class Query< enumerable: true, get: () => { if (abortController) { - this.abortSignalConsumed = true + this.#abortSignalConsumed = true return abortController.signal } return undefined @@ -393,7 +395,7 @@ export class Query< if (!this.options.queryFn) { return Promise.reject('Missing queryFn') } - this.abortSignalConsumed = false + this.#abortSignalConsumed = false return this.options.queryFn(queryFnContext) } @@ -418,13 +420,13 @@ export class Query< this.state.fetchStatus === 'idle' || this.state.fetchMeta !== context.fetchOptions?.meta ) { - this.dispatch({ type: 'fetch', meta: context.fetchOptions?.meta }) + this.#dispatch({ type: 'fetch', meta: context.fetchOptions?.meta }) } const onError = (error: TError | { silent?: boolean }) => { // Optimistically update state if needed if (!(isCancelledError(error) && error.silent)) { - this.dispatch({ + this.#dispatch({ type: 'error', error: error as TError, }) @@ -432,10 +434,10 @@ export class Query< if (!isCancelledError(error)) { // Notify cache callback - this.cache.config.onError?.(error, this as Query) + this.#cache.config.onError?.(error, this as Query) if (process.env.NODE_ENV !== 'production') { - this.logger.error(error) + this.#logger.error(error) } } @@ -447,13 +449,13 @@ export class Query< } // Try to fetch the data - this.retryer = createRetryer({ + this.#retryer = createRetryer({ fn: context.fetchFn as () => TData, abort: abortController?.abort.bind(abortController), onSuccess: (data) => { if (typeof data === 'undefined') { if (process.env.NODE_ENV !== 'production') { - this.logger.error( + this.#logger.error( `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`, ) } @@ -464,7 +466,7 @@ export class Query< this.setData(data as TData) // Notify cache callback - this.cache.config.onSuccess?.(data, this as Query) + this.#cache.config.onSuccess?.(data, this as Query) if (!this.isFetchingOptimistic) { // Schedule query gc after fetching @@ -474,25 +476,25 @@ export class Query< }, onError, onFail: (failureCount, error) => { - this.dispatch({ type: 'failed', failureCount, error }) + this.#dispatch({ type: 'failed', failureCount, error }) }, onPause: () => { - this.dispatch({ type: 'pause' }) + this.#dispatch({ type: 'pause' }) }, onContinue: () => { - this.dispatch({ type: 'continue' }) + this.#dispatch({ type: 'continue' }) }, retry: context.options.retry, retryDelay: context.options.retryDelay, networkMode: context.options.networkMode, }) - this.promise = this.retryer.promise + this.#promise = this.#retryer.promise - return this.promise + return this.#promise } - private dispatch(action: Action): void { + #dispatch(action: Action): void { const reducer = ( state: QueryState, ): QueryState => { @@ -575,11 +577,11 @@ export class Query< this.state = reducer(this.state) notifyManager.batch(() => { - this.observers.forEach((observer) => { + this.#observers.forEach((observer) => { observer.onQueryUpdate(action) }) - this.cache.notify({ query: this, type: 'updated', action }) + this.#cache.notify({ query: this, type: 'updated', action }) }) } } diff --git a/packages/query-core/src/queryCache.ts b/packages/query-core/src/queryCache.ts index 78dad1b87d2..e4c0ac71281 100644 --- a/packages/query-core/src/queryCache.ts +++ b/packages/query-core/src/queryCache.ts @@ -74,14 +74,14 @@ type QueryCacheListener = (event: QueryCacheNotifyEvent) => void export class QueryCache extends Subscribable { config: QueryCacheConfig - private queries: Query[] - private queriesMap: QueryHashMap + #queries: Query[] + #queriesMap: QueryHashMap constructor(config?: QueryCacheConfig) { super() this.config = config || {} - this.queries = [] - this.queriesMap = {} + this.#queries = [] + this.#queriesMap = {} } build( @@ -111,9 +111,9 @@ export class QueryCache extends Subscribable { } add(query: Query): void { - if (!this.queriesMap[query.queryHash]) { - this.queriesMap[query.queryHash] = query - this.queries.push(query) + if (!this.#queriesMap[query.queryHash]) { + this.#queriesMap[query.queryHash] = query + this.#queries.push(query) this.notify({ type: 'added', query, @@ -122,15 +122,15 @@ export class QueryCache extends Subscribable { } remove(query: Query): void { - const queryInMap = this.queriesMap[query.queryHash] + const queryInMap = this.#queriesMap[query.queryHash] if (queryInMap) { query.destroy() - this.queries = this.queries.filter((x) => x !== query) + this.#queries = this.#queries.filter((x) => x !== query) if (queryInMap === query) { - delete this.queriesMap[query.queryHash] + delete this.#queriesMap[query.queryHash] } this.notify({ type: 'removed', query }) @@ -139,7 +139,7 @@ export class QueryCache extends Subscribable { clear(): void { notifyManager.batch(() => { - this.queries.forEach((query) => { + this.#queries.forEach((query) => { this.remove(query) }) }) @@ -153,11 +153,11 @@ export class QueryCache extends Subscribable { >( queryHash: string, ): Query | undefined { - return this.queriesMap[queryHash] + return this.#queriesMap[queryHash] } getAll(): Query[] { - return this.queries + return this.#queries } find( @@ -167,13 +167,13 @@ export class QueryCache extends Subscribable { filters.exact = true } - return this.queries.find((query) => matchQuery(filters, query)) + return this.#queries.find((query) => matchQuery(filters, query)) } findAll(filters: QueryFilters = {}): Query[] { return Object.keys(filters).length > 0 - ? this.queries.filter((query) => matchQuery(filters, query)) - : this.queries + ? this.#queries.filter((query) => matchQuery(filters, query)) + : this.#queries } notify(event: QueryCacheNotifyEvent) { @@ -186,7 +186,7 @@ export class QueryCache extends Subscribable { onFocus(): void { notifyManager.batch(() => { - this.queries.forEach((query) => { + this.#queries.forEach((query) => { query.onFocus() }) }) @@ -194,7 +194,7 @@ export class QueryCache extends Subscribable { onOnline(): void { notifyManager.batch(() => { - this.queries.forEach((query) => { + this.#queries.forEach((query) => { query.onOnline() }) }) diff --git a/packages/query-core/src/queryClient.ts b/packages/query-core/src/queryClient.ts index 7888a22ac55..9e7062511ba 100644 --- a/packages/query-core/src/queryClient.ts +++ b/packages/query-core/src/queryClient.ts @@ -52,74 +52,74 @@ interface MutationDefaults { // CLASS export class QueryClient { - private queryCache: QueryCache - private mutationCache: MutationCache - private logger: Logger - private defaultOptions: DefaultOptions - private queryDefaults: QueryDefaults[] - private mutationDefaults: MutationDefaults[] - private mountCount: number - private unsubscribeFocus?: () => void - private unsubscribeOnline?: () => void + #queryCache: QueryCache + #mutationCache: MutationCache + #logger: Logger + #defaultOptions: DefaultOptions + #queryDefaults: QueryDefaults[] + #mutationDefaults: MutationDefaults[] + #mountCount: number + #unsubscribeFocus?: () => void + #unsubscribeOnline?: () => void constructor(config: QueryClientConfig = {}) { - this.queryCache = config.queryCache || new QueryCache() - this.mutationCache = config.mutationCache || new MutationCache() - this.logger = config.logger || defaultLogger - this.defaultOptions = config.defaultOptions || {} - this.queryDefaults = [] - this.mutationDefaults = [] - this.mountCount = 0 + this.#queryCache = config.queryCache || new QueryCache() + this.#mutationCache = config.mutationCache || new MutationCache() + this.#logger = config.logger || defaultLogger + this.#defaultOptions = config.defaultOptions || {} + this.#queryDefaults = [] + this.#mutationDefaults = [] + this.#mountCount = 0 if (process.env.NODE_ENV !== 'production' && config.logger) { - this.logger.error( + this.#logger.error( `Passing a custom logger has been deprecated and will be removed in the next major version.`, ) } } mount(): void { - this.mountCount++ - if (this.mountCount !== 1) return + this.#mountCount++ + if (this.#mountCount !== 1) return - this.unsubscribeFocus = focusManager.subscribe(() => { + this.#unsubscribeFocus = focusManager.subscribe(() => { if (focusManager.isFocused()) { this.resumePausedMutations() - this.queryCache.onFocus() + this.#queryCache.onFocus() } }) - this.unsubscribeOnline = onlineManager.subscribe(() => { + this.#unsubscribeOnline = onlineManager.subscribe(() => { if (onlineManager.isOnline()) { this.resumePausedMutations() - this.queryCache.onOnline() + this.#queryCache.onOnline() } }) } unmount(): void { - this.mountCount-- - if (this.mountCount !== 0) return + this.#mountCount-- + if (this.#mountCount !== 0) return - this.unsubscribeFocus?.() - this.unsubscribeFocus = undefined + this.#unsubscribeFocus?.() + this.#unsubscribeFocus = undefined - this.unsubscribeOnline?.() - this.unsubscribeOnline = undefined + this.#unsubscribeOnline?.() + this.#unsubscribeOnline = undefined } isFetching(filters: QueryFilters = {}): number { filters.fetchStatus = 'fetching' - return this.queryCache.findAll(filters).length + return this.#queryCache.findAll(filters).length } isMutating(filters?: MutationFilters): number { - return this.mutationCache.findAll({ ...filters, fetching: true }).length + return this.#mutationCache.findAll({ ...filters, fetching: true }).length } getQueryData( queryKey: QueryKey, ): TQueryFnData | undefined { - return this.queryCache.find({ queryKey })?.state.data + return this.#queryCache.find({ queryKey })?.state.data } ensureQueryData< @@ -151,7 +151,7 @@ export class QueryClient { updater: Updater, options?: SetDataOptions, ): TQueryFnData | undefined { - const query = this.queryCache.find({ queryKey }) + const query = this.#queryCache.find({ queryKey }) const prevData = query?.state.data const data = functionalUpdate(updater, prevData) @@ -167,7 +167,7 @@ export class QueryClient { QueryKey >({ queryKey }) - return this.queryCache + return this.#queryCache .build(this, defaultedOptions) .setData(data, { ...options, manual: true }) } @@ -190,11 +190,11 @@ export class QueryClient { getQueryState( queryKey: QueryKey, ): QueryState | undefined { - return this.queryCache.find({ queryKey })?.state + return this.#queryCache.find({ queryKey })?.state } removeQueries(filters?: QueryFilters): void { - const queryCache = this.queryCache + const queryCache = this.#queryCache notifyManager.batch(() => { queryCache.findAll(filters).forEach((query) => { queryCache.remove(query) @@ -206,7 +206,7 @@ export class QueryClient { filters?: ResetQueryFilters, options?: ResetOptions, ): Promise { - const queryCache = this.queryCache + const queryCache = this.#queryCache const refetchFilters: RefetchQueryFilters = { type: 'active', @@ -230,7 +230,7 @@ export class QueryClient { } const promises = notifyManager.batch(() => - this.queryCache + this.#queryCache .findAll(filters) .map((query) => query.cancel(cancelOptions)), ) @@ -243,7 +243,7 @@ export class QueryClient { options: InvalidateOptions = {}, ): Promise { return notifyManager.batch(() => { - this.queryCache.findAll(filters).forEach((query) => { + this.#queryCache.findAll(filters).forEach((query) => { query.invalidate() }) @@ -263,7 +263,7 @@ export class QueryClient { options?: RefetchOptions, ): Promise { const promises = notifyManager.batch(() => - this.queryCache + this.#queryCache .findAll(filters) .filter((query) => !query.isDisabled()) .map((query) => @@ -299,7 +299,7 @@ export class QueryClient { defaultedOptions.retry = false } - const query = this.queryCache.build(this, defaultedOptions) + const query = this.#queryCache.build(this, defaultedOptions) return query.isStaleByTime(defaultedOptions.staleTime) ? query.fetch(defaultedOptions) @@ -341,40 +341,40 @@ export class QueryClient { } resumePausedMutations(): Promise { - return this.mutationCache.resumePausedMutations() + return this.#mutationCache.resumePausedMutations() } getQueryCache(): QueryCache { - return this.queryCache + return this.#queryCache } getMutationCache(): MutationCache { - return this.mutationCache + return this.#mutationCache } getLogger(): Logger { - return this.logger + return this.#logger } getDefaultOptions(): DefaultOptions { - return this.defaultOptions + return this.#defaultOptions } setDefaultOptions(options: DefaultOptions): void { - this.defaultOptions = options + this.#defaultOptions = options } setQueryDefaults( queryKey: QueryKey, options: Omit, 'queryKey'>, ): void { - const result = this.queryDefaults.find( + const result = this.#queryDefaults.find( (x) => hashQueryKey(queryKey) === hashQueryKey(x.queryKey), ) if (result) { result.defaultOptions = options } else { - this.queryDefaults.push({ queryKey, defaultOptions: options }) + this.#queryDefaults.push({ queryKey, defaultOptions: options }) } } @@ -386,19 +386,19 @@ export class QueryClient { } // Get the first matching defaults - const firstMatchingDefaults = this.queryDefaults.find((x) => + const firstMatchingDefaults = this.#queryDefaults.find((x) => partialMatchKey(queryKey, x.queryKey), ) // Additional checks and error in dev mode if (process.env.NODE_ENV !== 'production') { // Retrieve all matching defaults for the given key - const matchingDefaults = this.queryDefaults.filter((x) => + const matchingDefaults = this.#queryDefaults.filter((x) => partialMatchKey(queryKey, x.queryKey), ) // It is ok not having defaults, but it is error prone to have more than 1 default for a given key if (matchingDefaults.length > 1) { - this.logger.error( + this.#logger.error( `[QueryClient] Several query defaults match with key '${JSON.stringify( queryKey, )}'. The first matching query defaults are used. Please check how query defaults are registered. Order does matter here. cf. https://react-query.tanstack.com/reference/QueryClient#queryclientsetquerydefaults.`, @@ -413,13 +413,13 @@ export class QueryClient { mutationKey: MutationKey, options: MutationObserverOptions, ): void { - const result = this.mutationDefaults.find( + const result = this.#mutationDefaults.find( (x) => hashQueryKey(mutationKey) === hashQueryKey(x.mutationKey), ) if (result) { result.defaultOptions = options } else { - this.mutationDefaults.push({ mutationKey, defaultOptions: options }) + this.#mutationDefaults.push({ mutationKey, defaultOptions: options }) } } @@ -431,19 +431,19 @@ export class QueryClient { } // Get the first matching defaults - const firstMatchingDefaults = this.mutationDefaults.find((x) => + const firstMatchingDefaults = this.#mutationDefaults.find((x) => partialMatchKey(mutationKey, x.mutationKey), ) // Additional checks and error in dev mode if (process.env.NODE_ENV !== 'production') { // Retrieve all matching defaults for the given key - const matchingDefaults = this.mutationDefaults.filter((x) => + const matchingDefaults = this.#mutationDefaults.filter((x) => partialMatchKey(mutationKey, x.mutationKey), ) // It is ok not having defaults, but it is error prone to have more than 1 default for a given key if (matchingDefaults.length > 1) { - this.logger.error( + this.#logger.error( `[QueryClient] Several mutation defaults match with key '${JSON.stringify( mutationKey, )}'. The first matching mutation defaults are used. Please check how mutation defaults are registered. Order does matter here. cf. https://react-query.tanstack.com/reference/QueryClient#queryclientsetmutationdefaults.`, @@ -488,7 +488,7 @@ export class QueryClient { } const defaultedOptions = { - ...this.defaultOptions.queries, + ...this.#defaultOptions.queries, ...this.getQueryDefaults(options?.queryKey), ...options, _defaulted: true, @@ -526,7 +526,7 @@ export class QueryClient { return options } return { - ...this.defaultOptions.mutations, + ...this.#defaultOptions.mutations, ...this.getMutationDefaults(options?.mutationKey), ...options, _defaulted: true, @@ -534,7 +534,7 @@ export class QueryClient { } clear(): void { - this.queryCache.clear() - this.mutationCache.clear() + this.#queryCache.clear() + this.#mutationCache.clear() } } diff --git a/packages/query-core/src/queryObserver.ts b/packages/query-core/src/queryObserver.ts index 96ccd0a3786..57067d88d0e 100644 --- a/packages/query-core/src/queryObserver.ts +++ b/packages/query-core/src/queryObserver.ts @@ -53,26 +53,26 @@ export class QueryObserver< TQueryKey > - private client: QueryClient - private currentQuery!: Query - private currentQueryInitialState!: QueryState - private currentResult!: QueryObserverResult - private currentResultState?: QueryState - private currentResultOptions?: QueryObserverOptions< + #client: QueryClient + #currentQuery: Query = undefined! + #currentQueryInitialState: QueryState = undefined! + #currentResult: QueryObserverResult = undefined! + #currentResultState?: QueryState + #currentResultOptions?: QueryObserverOptions< TQueryFnData, TError, TData, TQueryData, TQueryKey > - private previousQueryResult?: QueryObserverResult - private selectError: TError | null - private selectFn?: (data: TQueryData) => TData - private selectResult?: TData - private staleTimeoutId?: ReturnType - private refetchIntervalId?: ReturnType - private currentRefetchInterval?: number | false - private trackedProps!: Set + #previousQueryResult?: QueryObserverResult + #selectError: TError | null + #selectFn?: (data: TQueryData) => TData + #selectResult?: TData + #staleTimeoutId?: ReturnType + #refetchIntervalId?: ReturnType + #currentRefetchInterval?: number | false + #trackedProps: Set = new Set() constructor( client: QueryClient, @@ -86,10 +86,9 @@ export class QueryObserver< ) { super() - this.client = client + this.#client = client this.options = options - this.trackedProps = new Set() - this.selectError = null + this.#selectError = null this.bindMethods() this.setOptions(options) } @@ -100,13 +99,13 @@ export class QueryObserver< protected onSubscribe(): void { if (this.listeners.length === 1) { - this.currentQuery.addObserver(this) + this.#currentQuery.addObserver(this) - if (shouldFetchOnMount(this.currentQuery, this.options)) { - this.executeFetch() + if (shouldFetchOnMount(this.#currentQuery, this.options)) { + this.#executeFetch() } - this.updateTimers() + this.#updateTimers() } } @@ -118,7 +117,7 @@ export class QueryObserver< shouldFetchOnReconnect(): boolean { return shouldFetchOn( - this.currentQuery, + this.#currentQuery, this.options, this.options.refetchOnReconnect, ) @@ -126,7 +125,7 @@ export class QueryObserver< shouldFetchOnWindowFocus(): boolean { return shouldFetchOn( - this.currentQuery, + this.#currentQuery, this.options, this.options.refetchOnWindowFocus, ) @@ -134,9 +133,9 @@ export class QueryObserver< destroy(): void { this.listeners = [] - this.clearStaleTimeout() - this.clearRefetchInterval() - this.currentQuery.removeObserver(this) + this.#clearStaleTimeout() + this.#clearRefetchInterval() + this.#currentQuery.removeObserver(this) } setOptions( @@ -150,14 +149,14 @@ export class QueryObserver< notifyOptions?: NotifyOptions, ): void { const prevOptions = this.options - const prevQuery = this.currentQuery + const prevQuery = this.#currentQuery - this.options = this.client.defaultQueryOptions(options) + this.options = this.#client.defaultQueryOptions(options) if (!shallowEqualObjects(prevOptions, this.options)) { - this.client.getQueryCache().notify({ + this.#client.getQueryCache().notify({ type: 'observerOptionsUpdated', - query: this.currentQuery, + query: this.#currentQuery, observer: this, }) } @@ -174,7 +173,7 @@ export class QueryObserver< this.options.queryKey = prevOptions.queryKey } - this.updateQuery() + this.#updateQuery() const mounted = this.hasListeners() @@ -182,13 +181,13 @@ export class QueryObserver< if ( mounted && shouldFetchOptionally( - this.currentQuery, + this.#currentQuery, prevQuery, this.options, prevOptions, ) ) { - this.executeFetch() + this.#executeFetch() } // Update result @@ -197,23 +196,23 @@ export class QueryObserver< // Update stale interval if needed if ( mounted && - (this.currentQuery !== prevQuery || + (this.#currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || this.options.staleTime !== prevOptions.staleTime) ) { - this.updateStaleTimeout() + this.#updateStaleTimeout() } - const nextRefetchInterval = this.computeRefetchInterval() + const nextRefetchInterval = this.#computeRefetchInterval() // Update refetch interval if needed if ( mounted && - (this.currentQuery !== prevQuery || + (this.#currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || - nextRefetchInterval !== this.currentRefetchInterval) + nextRefetchInterval !== this.#currentRefetchInterval) ) { - this.updateRefetchInterval(nextRefetchInterval) + this.#updateRefetchInterval(nextRefetchInterval) } } @@ -226,13 +225,13 @@ export class QueryObserver< TQueryKey >, ): QueryObserverResult { - const query = this.client.getQueryCache().build(this.client, options) + const query = this.#client.getQueryCache().build(this.#client, options) return this.createResult(query, options) } getCurrentResult(): QueryObserverResult { - return this.currentResult + return this.#currentResult } trackResult( @@ -245,7 +244,7 @@ export class QueryObserver< configurable: false, enumerable: true, get: () => { - this.trackedProps.add(key as keyof QueryObserverResult) + this.#trackedProps.add(key as keyof QueryObserverResult) return result[key as keyof QueryObserverResult] }, }) @@ -255,7 +254,7 @@ export class QueryObserver< } getCurrentQuery(): Query { - return this.currentQuery + return this.#currentQuery } refetch({ @@ -279,11 +278,11 @@ export class QueryObserver< TQueryKey >, ): Promise> { - const defaultedOptions = this.client.defaultQueryOptions(options) + const defaultedOptions = this.#client.defaultQueryOptions(options) - const query = this.client + const query = this.#client .getQueryCache() - .build(this.client, defaultedOptions) + .build(this.#client, defaultedOptions) query.isFetchingOptimistic = true return query.fetch().then(() => this.createResult(query, defaultedOptions)) @@ -292,23 +291,23 @@ export class QueryObserver< protected fetch( fetchOptions: ObserverFetchOptions, ): Promise> { - return this.executeFetch({ + return this.#executeFetch({ ...fetchOptions, cancelRefetch: fetchOptions.cancelRefetch ?? true, }).then(() => { this.updateResult() - return this.currentResult + return this.#currentResult }) } - private executeFetch( + #executeFetch( fetchOptions?: ObserverFetchOptions, ): Promise { // Make sure we reference the latest query as the current one might have been removed - this.updateQuery() + this.#updateQuery() // Fetch - let promise: Promise = this.currentQuery.fetch( + let promise: Promise = this.#currentQuery.fetch( this.options as QueryOptions, fetchOptions, ) @@ -320,19 +319,19 @@ export class QueryObserver< return promise } - private updateStaleTimeout(): void { - this.clearStaleTimeout() + #updateStaleTimeout(): void { + this.#clearStaleTimeout() if ( isServer || - this.currentResult.isStale || + this.#currentResult.isStale || !isValidTimeout(this.options.staleTime) ) { return } const time = timeUntilStale( - this.currentResult.dataUpdatedAt, + this.#currentResult.dataUpdatedAt, this.options.staleTime, ) @@ -340,59 +339,62 @@ export class QueryObserver< // To mitigate this issue we always add 1 ms to the timeout. const timeout = time + 1 - this.staleTimeoutId = setTimeout(() => { - if (!this.currentResult.isStale) { + this.#staleTimeoutId = setTimeout(() => { + if (!this.#currentResult.isStale) { this.updateResult() } }, timeout) } - private computeRefetchInterval() { + #computeRefetchInterval() { return typeof this.options.refetchInterval === 'function' - ? this.options.refetchInterval(this.currentResult.data, this.currentQuery) + ? this.options.refetchInterval( + this.#currentResult.data, + this.#currentQuery, + ) : this.options.refetchInterval ?? false } - private updateRefetchInterval(nextInterval: number | false): void { - this.clearRefetchInterval() + #updateRefetchInterval(nextInterval: number | false): void { + this.#clearRefetchInterval() - this.currentRefetchInterval = nextInterval + this.#currentRefetchInterval = nextInterval if ( isServer || this.options.enabled === false || - !isValidTimeout(this.currentRefetchInterval) || - this.currentRefetchInterval === 0 + !isValidTimeout(this.#currentRefetchInterval) || + this.#currentRefetchInterval === 0 ) { return } - this.refetchIntervalId = setInterval(() => { + this.#refetchIntervalId = setInterval(() => { if ( this.options.refetchIntervalInBackground || focusManager.isFocused() ) { - this.executeFetch() + this.#executeFetch() } - }, this.currentRefetchInterval) + }, this.#currentRefetchInterval) } - private updateTimers(): void { - this.updateStaleTimeout() - this.updateRefetchInterval(this.computeRefetchInterval()) + #updateTimers(): void { + this.#updateStaleTimeout() + this.#updateRefetchInterval(this.#computeRefetchInterval()) } - private clearStaleTimeout(): void { - if (this.staleTimeoutId) { - clearTimeout(this.staleTimeoutId) - this.staleTimeoutId = undefined + #clearStaleTimeout(): void { + if (this.#staleTimeoutId) { + clearTimeout(this.#staleTimeoutId) + this.#staleTimeoutId = undefined } } - private clearRefetchInterval(): void { - if (this.refetchIntervalId) { - clearInterval(this.refetchIntervalId) - this.refetchIntervalId = undefined + #clearRefetchInterval(): void { + if (this.#refetchIntervalId) { + clearInterval(this.#refetchIntervalId) + this.#refetchIntervalId = undefined } } @@ -406,20 +408,20 @@ export class QueryObserver< TQueryKey >, ): QueryObserverResult { - const prevQuery = this.currentQuery + const prevQuery = this.#currentQuery const prevOptions = this.options - const prevResult = this.currentResult as + const prevResult = this.#currentResult as | QueryObserverResult | undefined - const prevResultState = this.currentResultState - const prevResultOptions = this.currentResultOptions + const prevResultState = this.#currentResultState + const prevResultOptions = this.#currentResultOptions const queryChange = query !== prevQuery const queryInitialState = queryChange ? query.state - : this.currentQueryInitialState + : this.#currentQueryInitialState const prevQueryResult = queryChange - ? this.currentResult - : this.previousQueryResult + ? this.#currentResult + : this.#previousQueryResult const { state } = query let { dataUpdatedAt, error, errorUpdatedAt, fetchStatus, status } = state @@ -467,21 +469,21 @@ export class QueryObserver< if ( prevResult && state.data === prevResultState?.data && - options.select === this.selectFn + options.select === this.#selectFn ) { - data = this.selectResult + data = this.#selectResult } else { try { - this.selectFn = options.select + this.#selectFn = options.select data = options.select(state.data) data = replaceData(prevResult?.data, data, options) - this.selectResult = data - this.selectError = null + this.#selectResult = data + this.#selectError = null } catch (selectError) { if (process.env.NODE_ENV !== 'production') { - this.client.getLogger().error(selectError) + this.#client.getLogger().error(selectError) } - this.selectError = selectError as TError + this.#selectError = selectError as TError } } } @@ -512,12 +514,12 @@ export class QueryObserver< if (options.select && typeof placeholderData !== 'undefined') { try { placeholderData = options.select(placeholderData) - this.selectError = null + this.#selectError = null } catch (selectError) { if (process.env.NODE_ENV !== 'production') { - this.client.getLogger().error(selectError) + this.#client.getLogger().error(selectError) } - this.selectError = selectError as TError + this.#selectError = selectError as TError } } } @@ -529,9 +531,9 @@ export class QueryObserver< } } - if (this.selectError) { - error = this.selectError as any - data = this.selectResult + if (this.#selectError) { + error = this.#selectError as any + data = this.#selectResult errorUpdatedAt = Date.now() status = 'error' } @@ -573,20 +575,20 @@ export class QueryObserver< } updateResult(notifyOptions?: NotifyOptions): void { - const prevResult = this.currentResult as + const prevResult = this.#currentResult as | QueryObserverResult | undefined - const nextResult = this.createResult(this.currentQuery, this.options) - this.currentResultState = this.currentQuery.state - this.currentResultOptions = this.options + const nextResult = this.createResult(this.#currentQuery, this.options) + this.#currentResultState = this.#currentQuery.state + this.#currentResultOptions = this.options // Only notify and update result if something has changed if (shallowEqualObjects(nextResult, prevResult)) { return } - this.currentResult = nextResult + this.#currentResult = nextResult // Determine which callbacks to trigger const defaultNotifyOptions: NotifyOptions = { cache: true } @@ -600,20 +602,20 @@ export class QueryObserver< if ( notifyOnChangeProps === 'all' || - (!notifyOnChangeProps && !this.trackedProps.size) + (!notifyOnChangeProps && !this.#trackedProps.size) ) { return true } - const includedProps = new Set(notifyOnChangeProps ?? this.trackedProps) + const includedProps = new Set(notifyOnChangeProps ?? this.#trackedProps) if (this.options.throwErrors) { includedProps.add('error') } - return Object.keys(this.currentResult).some((key) => { + return Object.keys(this.#currentResult).some((key) => { const typedKey = key as keyof QueryObserverResult - const changed = this.currentResult[typedKey] !== prevResult[typedKey] + const changed = this.#currentResult[typedKey] !== prevResult[typedKey] return changed && includedProps.has(typedKey) }) } @@ -622,22 +624,22 @@ export class QueryObserver< defaultNotifyOptions.listeners = true } - this.notify({ ...defaultNotifyOptions, ...notifyOptions }) + this.#notify({ ...defaultNotifyOptions, ...notifyOptions }) } - private updateQuery(): void { - const query = this.client.getQueryCache().build(this.client, this.options) + #updateQuery(): void { + const query = this.#client.getQueryCache().build(this.#client, this.options) - if (query === this.currentQuery) { + if (query === this.#currentQuery) { return } - const prevQuery = this.currentQuery as + const prevQuery = this.#currentQuery as | Query | undefined - this.currentQuery = query - this.currentQueryInitialState = query.state - this.previousQueryResult = this.currentResult + this.#currentQuery = query + this.#currentQueryInitialState = query.state + this.#previousQueryResult = this.#currentResult if (this.hasListeners()) { prevQuery?.removeObserver(this) @@ -657,32 +659,32 @@ export class QueryObserver< this.updateResult(notifyOptions) if (this.hasListeners()) { - this.updateTimers() + this.#updateTimers() } } - private notify(notifyOptions: NotifyOptions): void { + #notify(notifyOptions: NotifyOptions): void { notifyManager.batch(() => { // First trigger the configuration callbacks if (notifyOptions.onSuccess) { - this.options.onSuccess?.(this.currentResult.data!) - this.options.onSettled?.(this.currentResult.data!, null) + this.options.onSuccess?.(this.#currentResult.data!) + this.options.onSettled?.(this.#currentResult.data!, null) } else if (notifyOptions.onError) { - this.options.onError?.(this.currentResult.error!) - this.options.onSettled?.(undefined, this.currentResult.error!) + this.options.onError?.(this.#currentResult.error!) + this.options.onSettled?.(undefined, this.#currentResult.error!) } // Then trigger the listeners if (notifyOptions.listeners) { this.listeners.forEach((listener) => { - listener(this.currentResult) + listener(this.#currentResult) }) } // Then the cache listeners if (notifyOptions.cache) { - this.client.getQueryCache().notify({ - query: this.currentQuery, + this.#client.getQueryCache().notify({ + query: this.#currentQuery, type: 'observerResultsUpdated', }) } diff --git a/packages/query-core/src/removable.ts b/packages/query-core/src/removable.ts index 8d06cfc585d..5b257fa6ea4 100644 --- a/packages/query-core/src/removable.ts +++ b/packages/query-core/src/removable.ts @@ -2,7 +2,7 @@ import { isServer, isValidTimeout } from './utils' export abstract class Removable { cacheTime!: number - private gcTimeout?: ReturnType + #gcTimeout?: ReturnType destroy(): void { this.clearGcTimeout() @@ -12,7 +12,7 @@ export abstract class Removable { this.clearGcTimeout() if (isValidTimeout(this.cacheTime)) { - this.gcTimeout = setTimeout(() => { + this.#gcTimeout = setTimeout(() => { this.optionalRemove() }, this.cacheTime) } @@ -27,9 +27,9 @@ export abstract class Removable { } protected clearGcTimeout() { - if (this.gcTimeout) { - clearTimeout(this.gcTimeout) - this.gcTimeout = undefined + if (this.#gcTimeout) { + clearTimeout(this.#gcTimeout) + this.#gcTimeout = undefined } } From 5ede05219cdba54a34db8a82f68ac3e7aa0d0d3b Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Thu, 5 Jan 2023 21:37:35 +0100 Subject: [PATCH 03/60] refactor: remove getAbortController function because with our new browserslist, we'll always have an AbortController --- packages/query-core/src/query.ts | 36 ++++++++++++++------------------ packages/query-core/src/types.ts | 2 +- packages/query-core/src/utils.ts | 7 ------- 3 files changed, 17 insertions(+), 28 deletions(-) diff --git a/packages/query-core/src/query.ts b/packages/query-core/src/query.ts index 5649b73d08f..a6b7f2a961f 100644 --- a/packages/query-core/src/query.ts +++ b/packages/query-core/src/query.ts @@ -1,4 +1,4 @@ -import { getAbortController, noop, replaceData, timeUntilStale } from './utils' +import { noop, replaceData, timeUntilStale } from './utils' import type { InitialDataFunction, QueryKey, @@ -59,7 +59,7 @@ export interface FetchContext< > { fetchFn: () => unknown | Promise fetchOptions?: FetchOptions - signal?: AbortSignal + signal: AbortSignal options: QueryOptions queryKey: TQueryKey state: QueryState @@ -363,10 +363,10 @@ export class Query< } } - const abortController = getAbortController() + const abortController = new AbortController() // Create query function context - const queryFnContext: QueryFunctionContext = { + const queryFnContext: Omit, 'signal'> = { queryKey: this.queryKey, pageParam: undefined, meta: this.meta, @@ -375,32 +375,30 @@ export class Query< // Adds an enumerable signal property to the object that // which sets abortSignalConsumed to true when the signal // is read. - const addSignalProperty = (object: unknown) => { - Object.defineProperty(object, 'signal', { + const withSignalProperty = (object: T): T & { signal: AbortSignal } => { + return Object.defineProperty(object, 'signal', { enumerable: true, get: () => { - if (abortController) { - this.#abortSignalConsumed = true - return abortController.signal - } - return undefined + this.#abortSignalConsumed = true + return abortController.signal }, - }) + }) as T & { signal: AbortSignal } } - addSignalProperty(queryFnContext) - // Create fetch function const fetchFn = () => { if (!this.options.queryFn) { return Promise.reject('Missing queryFn') } this.#abortSignalConsumed = false - return this.options.queryFn(queryFnContext) + return this.options.queryFn(withSignalProperty(queryFnContext)) } // Trigger behavior hook - const context: FetchContext = { + const context: Omit< + FetchContext, + 'signal' + > = { fetchOptions, options: this.options, queryKey: this.queryKey, @@ -408,9 +406,7 @@ export class Query< fetchFn, } - addSignalProperty(context) - - this.options.behavior?.onFetch(context) + this.options.behavior?.onFetch(withSignalProperty(context)) // Store state in case the current fetch needs to be reverted this.revertState = this.state @@ -451,7 +447,7 @@ export class Query< // Try to fetch the data this.#retryer = createRetryer({ fn: context.fetchFn as () => TData, - abort: abortController?.abort.bind(abortController), + abort: abortController.abort.bind(abortController), onSuccess: (data) => { if (typeof data === 'undefined') { if (process.env.NODE_ENV !== 'production') { diff --git a/packages/query-core/src/types.ts b/packages/query-core/src/types.ts index 16d538f9822..f177573d49f 100644 --- a/packages/query-core/src/types.ts +++ b/packages/query-core/src/types.ts @@ -20,7 +20,7 @@ export interface QueryFunctionContext< TPageParam = any, > { queryKey: TQueryKey - signal?: AbortSignal + signal: AbortSignal pageParam?: TPageParam meta: QueryMeta | undefined } diff --git a/packages/query-core/src/utils.ts b/packages/query-core/src/utils.ts index 5adf603245e..f06d514aea7 100644 --- a/packages/query-core/src/utils.ts +++ b/packages/query-core/src/utils.ts @@ -338,13 +338,6 @@ export function scheduleMicrotask(callback: () => void) { sleep(0).then(callback) } -export function getAbortController(): AbortController | undefined { - if (typeof AbortController === 'function') { - return new AbortController() - } - return -} - export function replaceData< TData, TOptions extends QueryOptions, From e577cc440cbd4f142bb563e2009753d218e2d2cb Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Thu, 5 Jan 2023 23:28:49 +0100 Subject: [PATCH 04/60] refactor: make updateResult private --- packages/query-core/src/queryObserver.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/query-core/src/queryObserver.ts b/packages/query-core/src/queryObserver.ts index 57067d88d0e..462c7d64281 100644 --- a/packages/query-core/src/queryObserver.ts +++ b/packages/query-core/src/queryObserver.ts @@ -191,7 +191,7 @@ export class QueryObserver< } // Update result - this.updateResult(notifyOptions) + this.#updateResult(notifyOptions) // Update stale interval if needed if ( @@ -295,7 +295,7 @@ export class QueryObserver< ...fetchOptions, cancelRefetch: fetchOptions.cancelRefetch ?? true, }).then(() => { - this.updateResult() + this.#updateResult() return this.#currentResult }) } @@ -341,7 +341,7 @@ export class QueryObserver< this.#staleTimeoutId = setTimeout(() => { if (!this.#currentResult.isStale) { - this.updateResult() + this.#updateResult() } }, timeout) } @@ -574,7 +574,7 @@ export class QueryObserver< return result as QueryObserverResult } - updateResult(notifyOptions?: NotifyOptions): void { + #updateResult(notifyOptions?: NotifyOptions): void { const prevResult = this.#currentResult as | QueryObserverResult | undefined @@ -656,7 +656,7 @@ export class QueryObserver< notifyOptions.onError = true } - this.updateResult(notifyOptions) + this.#updateResult(notifyOptions) if (this.hasListeners()) { this.#updateTimers() From c60fafeaad1252706a40bf38e49e69a94ae71801 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Thu, 5 Jan 2023 23:29:31 +0100 Subject: [PATCH 05/60] this didn't work returning the object and inlining the call yields "cannot redefine signal" ... --- packages/query-core/src/query.ts | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/packages/query-core/src/query.ts b/packages/query-core/src/query.ts index a6b7f2a961f..428da3a90f6 100644 --- a/packages/query-core/src/query.ts +++ b/packages/query-core/src/query.ts @@ -375,23 +375,27 @@ export class Query< // Adds an enumerable signal property to the object that // which sets abortSignalConsumed to true when the signal // is read. - const withSignalProperty = (object: T): T & { signal: AbortSignal } => { - return Object.defineProperty(object, 'signal', { + const addSignalProperty = (object: unknown) => { + Object.defineProperty(object, 'signal', { enumerable: true, get: () => { this.#abortSignalConsumed = true return abortController.signal }, - }) as T & { signal: AbortSignal } + }) } + addSignalProperty(queryFnContext) + // Create fetch function const fetchFn = () => { if (!this.options.queryFn) { return Promise.reject('Missing queryFn') } this.#abortSignalConsumed = false - return this.options.queryFn(withSignalProperty(queryFnContext)) + return this.options.queryFn( + queryFnContext as QueryFunctionContext, + ) } // Trigger behavior hook @@ -406,7 +410,11 @@ export class Query< fetchFn, } - this.options.behavior?.onFetch(withSignalProperty(context)) + addSignalProperty(context) + + this.options.behavior?.onFetch( + context as FetchContext, + ) // Store state in case the current fetch needs to be reverted this.revertState = this.state From f9b7eb577582f18dd40bb0cbcc0f208c2c05188f Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Thu, 5 Jan 2023 23:29:54 +0100 Subject: [PATCH 06/60] refactor: remove/move/inline some code --- packages/query-core/src/index.ts | 2 +- .../query-core/src/infiniteQueryBehavior.ts | 8 +++--- packages/query-core/src/queriesObserver.ts | 11 +++++++- packages/query-core/src/tests/query.test.tsx | 25 ++++++++----------- packages/query-core/src/utils.ts | 22 ++-------------- .../vue-query/src/__tests__/utils.test.ts | 8 +----- packages/vue-query/src/utils.ts | 9 ------- 7 files changed, 29 insertions(+), 56 deletions(-) diff --git a/packages/query-core/src/index.ts b/packages/query-core/src/index.ts index d2bee42dd84..241dd8f615d 100644 --- a/packages/query-core/src/index.ts +++ b/packages/query-core/src/index.ts @@ -11,7 +11,7 @@ export { MutationObserver } from './mutationObserver' export { notifyManager } from './notifyManager' export { focusManager } from './focusManager' export { onlineManager } from './onlineManager' -export { hashQueryKey, replaceEqualDeep, isError, isServer } from './utils' +export { hashQueryKey, replaceEqualDeep, isServer } from './utils' export type { MutationFilters, QueryFilters, Updater } from './utils' export { isCancelledError } from './retryer' export { dehydrate, hydrate } from './hydration' diff --git a/packages/query-core/src/infiniteQueryBehavior.ts b/packages/query-core/src/infiniteQueryBehavior.ts index b621b4013b8..b6989f0eb0b 100644 --- a/packages/query-core/src/infiniteQueryBehavior.ts +++ b/packages/query-core/src/infiniteQueryBehavior.ts @@ -30,10 +30,10 @@ export function infiniteQueryBehavior< Object.defineProperty(object, 'signal', { enumerable: true, get: () => { - if (context.signal?.aborted) { + if (context.signal.aborted) { cancelled = true } else { - context.signal?.addEventListener('abort', () => { + context.signal.addEventListener('abort', () => { cancelled = true }) } @@ -73,7 +73,7 @@ export function infiniteQueryBehavior< return Promise.resolve(pages) } - const queryFnContext: QueryFunctionContext = { + const queryFnContext: Omit = { queryKey: context.queryKey, pageParam: param, meta: context.options.meta, @@ -81,7 +81,7 @@ export function infiniteQueryBehavior< addSignalProperty(queryFnContext) - const queryFnResult = queryFn(queryFnContext) + const queryFnResult = queryFn(queryFnContext as QueryFunctionContext) const promise = Promise.resolve(queryFnResult).then((page) => buildNewPages(pages, param, page, previous), diff --git a/packages/query-core/src/queriesObserver.ts b/packages/query-core/src/queriesObserver.ts index 387d553ebe2..e9591db59bd 100644 --- a/packages/query-core/src/queriesObserver.ts +++ b/packages/query-core/src/queriesObserver.ts @@ -1,4 +1,3 @@ -import { difference, replaceAt } from './utils' import { notifyManager } from './notifyManager' import type { QueryObserverOptions, @@ -10,6 +9,16 @@ import type { NotifyOptions } from './queryObserver' import { QueryObserver } from './queryObserver' import { Subscribable } from './subscribable' +function difference(array1: T[], array2: T[]): T[] { + return array1.filter((x) => array2.indexOf(x) === -1) +} + +function replaceAt(array: T[], index: number, value: T): T[] { + const copy = array.slice(0) + copy[index] = value + return copy +} + type QueriesObserverListener = (result: QueryObserverResult[]) => void export class QueriesObserver extends Subscribable { diff --git a/packages/query-core/src/tests/query.test.tsx b/packages/query-core/src/tests/query.test.tsx index 64c87be01ae..ca51051d7a5 100644 --- a/packages/query-core/src/tests/query.test.tsx +++ b/packages/query-core/src/tests/query.test.tsx @@ -11,7 +11,7 @@ import type { QueryFunctionContext, QueryObserverResult, } from '..' -import { QueryObserver, isCancelledError, isError, onlineManager } from '..' +import { QueryObserver, isCancelledError, onlineManager } from '..' import { waitFor } from '@testing-library/react' describe('query', () => { @@ -246,7 +246,7 @@ describe('query', () => { queryKey: key, queryFn: async ({ signal }) => { await sleep(100) - return signal?.aborted ? 'aborted' : 'data' + return signal.aborted ? 'aborted' : 'data' }, }) @@ -283,15 +283,11 @@ describe('query', () => { let error queryFn.mockImplementation(async ({ signal }) => { - if (signal) { - signal.onabort = onAbort - signal.addEventListener('abort', abortListener) - } + signal.onabort = onAbort + signal.addEventListener('abort', abortListener) await sleep(10) - if (signal) { - signal.onabort = null - signal.removeEventListener('abort', abortListener) - } + signal.onabort = null + signal.removeEventListener('abort', abortListener) throw new Error() }) @@ -311,7 +307,7 @@ describe('query', () => { expect(queryFn).toHaveBeenCalledTimes(1) const signal = queryFn.mock.calls[0]![0].signal - expect(signal?.aborted).toBe(false) + expect(signal.aborted).toBe(false) expect(onAbort).not.toHaveBeenCalled() expect(abortListener).not.toHaveBeenCalled() @@ -319,7 +315,7 @@ describe('query', () => { await sleep(100) - expect(signal?.aborted).toBe(true) + expect(signal.aborted).toBe(true) expect(onAbort).toHaveBeenCalledTimes(1) expect(abortListener).toHaveBeenCalledTimes(1) expect(isCancelledError(error)).toBe(true) @@ -422,18 +418,19 @@ describe('query', () => { test('cancelling a rejected query should not have any effect', async () => { const key = queryKey() + const error = new Error('error') await queryClient.prefetchQuery({ queryKey: key, queryFn: async (): Promise => { - throw new Error('error') + throw error }, }) const query = queryCache.find({ queryKey: key })! query.cancel() await sleep(10) - expect(isError(query.state.error)).toBe(true) + expect(query.state.error).toBe(error) expect(isCancelledError(query.state.error)).toBe(false) }) diff --git a/packages/query-core/src/utils.ts b/packages/query-core/src/utils.ts index f06d514aea7..e58f586e153 100644 --- a/packages/query-core/src/utils.ts +++ b/packages/query-core/src/utils.ts @@ -79,16 +79,6 @@ export function isValidTimeout(value: unknown): value is number { return typeof value === 'number' && value >= 0 && value !== Infinity } -export function difference(array1: T[], array2: T[]): T[] { - return array1.filter((x) => array2.indexOf(x) === -1) -} - -export function replaceAt(array: T[], index: number, value: T): T[] { - const copy = array.slice(0) - copy[index] = value - return copy -} - export function timeUntilStale(updatedAt: number, staleTime?: number): number { return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0) } @@ -106,7 +96,7 @@ export function matchQuery( stale, } = filters - if (isQueryKey(queryKey)) { + if (Array.isArray(queryKey)) { if (exact) { if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) { return false @@ -149,7 +139,7 @@ export function matchMutation( mutation: Mutation, ): boolean { const { exact, fetching, predicate, mutationKey } = filters - if (isQueryKey(mutationKey)) { + if (Array.isArray(mutationKey)) { if (!mutation.options.mutationKey) { return false } @@ -316,14 +306,6 @@ function hasObjectPrototype(o: any): boolean { return Object.prototype.toString.call(o) === '[object Object]' } -export function isQueryKey(value: unknown): value is QueryKey { - return Array.isArray(value) -} - -export function isError(value: any): value is Error { - return value instanceof Error -} - export function sleep(timeout: number): Promise { return new Promise((resolve) => { setTimeout(resolve, timeout) diff --git a/packages/vue-query/src/__tests__/utils.test.ts b/packages/vue-query/src/__tests__/utils.test.ts index 0b88356d4bf..e78570b1b73 100644 --- a/packages/vue-query/src/__tests__/utils.test.ts +++ b/packages/vue-query/src/__tests__/utils.test.ts @@ -1,13 +1,7 @@ -import { isQueryKey, updateState, cloneDeep, cloneDeepUnref } from '../utils' +import { updateState, cloneDeep, cloneDeepUnref } from '../utils' import { reactive, ref } from 'vue-demi' describe('utils', () => { - describe('isQueryKey', () => { - test('should detect an array as query key', () => { - expect(isQueryKey(['string', 'array'])).toEqual(true) - }) - }) - describe('updateState', () => { test('should update first object with values from the second one', () => { const origin = { option1: 'a', option2: 'b', option3: 'c' } diff --git a/packages/vue-query/src/utils.ts b/packages/vue-query/src/utils.ts index a754fc477cf..fc50f1ff263 100644 --- a/packages/vue-query/src/utils.ts +++ b/packages/vue-query/src/utils.ts @@ -1,5 +1,4 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ -import type { QueryKey, MutationKey } from '@tanstack/query-core' import { isRef, unref } from 'vue-demi' import type { UnwrapRef } from 'vue-demi' @@ -10,14 +9,6 @@ export function getClientKey(key?: string) { return `${VUE_QUERY_CLIENT}${suffix}` } -export function isQueryKey(value: unknown): value is QueryKey { - return Array.isArray(value) -} - -export function isMutationKey(value: unknown): value is MutationKey { - return Array.isArray(value) -} - export function updateState( state: Record, update: Record, From 0efc1c95fed6626fe0489160b8ea7e03fca8501b Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Thu, 5 Jan 2023 23:41:43 +0100 Subject: [PATCH 07/60] tests: focusManager fix focusManager tests by not accessing private methods --- .../query-core/src/tests/focusManager.test.tsx | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/packages/query-core/src/tests/focusManager.test.tsx b/packages/query-core/src/tests/focusManager.test.tsx index 645a93f477e..e8f698e6977 100644 --- a/packages/query-core/src/tests/focusManager.test.tsx +++ b/packages/query-core/src/tests/focusManager.test.tsx @@ -63,26 +63,34 @@ describe('focusManager', () => { globalThis.document = document }) - test('cleanup should still be undefined if window is not defined', async () => { + test('cleanup (removeEventListener) should not be called if window is not defined', async () => { const restoreIsServer = setIsServer(true) + const removeEventListenerSpy = jest.spyOn(globalThis, 'removeEventListener') + const unsubscribe = focusManager.subscribe(() => undefined) - expect(focusManager['cleanup']).toBeUndefined() unsubscribe() + + expect(removeEventListenerSpy).not.toHaveBeenCalled() + restoreIsServer() }) - test('cleanup should still be undefined if window.addEventListener is not defined', async () => { + test('cleanup (removeEventListener) should not be called if window.addEventListener is not defined', async () => { const { addEventListener } = globalThis.window // @ts-expect-error globalThis.window.addEventListener = undefined + const removeEventListenerSpy = jest.spyOn(globalThis, 'removeEventListener') + const unsubscribe = focusManager.subscribe(() => undefined) - expect(focusManager['cleanup']).toBeUndefined() unsubscribe() + + expect(removeEventListenerSpy).not.toHaveBeenCalled() + globalThis.window.addEventListener = addEventListener }) From 0832d01e313ede5ad419d5e749cd4bc462b8f790 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Thu, 5 Jan 2023 23:53:03 +0100 Subject: [PATCH 08/60] tests: mutationCache remove a test that tests an impossible case --- .../src/tests/mutationCache.test.tsx | 40 ------------------- 1 file changed, 40 deletions(-) diff --git a/packages/query-core/src/tests/mutationCache.test.tsx b/packages/query-core/src/tests/mutationCache.test.tsx index bb4f93c1451..eeb7ec7c0df 100644 --- a/packages/query-core/src/tests/mutationCache.test.tsx +++ b/packages/query-core/src/tests/mutationCache.test.tsx @@ -241,46 +241,6 @@ describe('mutationCache', () => { }) }) - test('should only remove when the last observer unsubscribes', async () => { - const queryClient = createQueryClient() - const observer1 = new MutationObserver(queryClient, { - variables: 1, - cacheTime: 10, - mutationFn: async () => { - await sleep(10) - return 'update1' - }, - }) - - const observer2 = new MutationObserver(queryClient, { - cacheTime: 10, - mutationFn: async () => { - await sleep(10) - return 'update2' - }, - }) - - await observer1.mutate() - - // we currently have no way to add multiple observers to the same mutation - const currentMutation = observer1['currentMutation']! - currentMutation.addObserver(observer1) - currentMutation.addObserver(observer2) - - expect(currentMutation['observers'].length).toEqual(2) - expect(queryClient.getMutationCache().getAll()).toHaveLength(1) - - currentMutation.removeObserver(observer1) - currentMutation.removeObserver(observer2) - expect(currentMutation['observers'].length).toEqual(0) - expect(queryClient.getMutationCache().getAll()).toHaveLength(1) - // wait for cacheTime to gc - await sleep(10) - await waitFor(() => { - expect(queryClient.getMutationCache().getAll()).toHaveLength(0) - }) - }) - test('should be garbage collected later when unsubscribed and mutation is loading', async () => { const queryClient = createQueryClient() const onSuccess = jest.fn() From 747a2b52c8bfe1cda12e37b125c6f39b4bf9d41d Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Thu, 5 Jan 2023 23:55:46 +0100 Subject: [PATCH 09/60] refactor: mutationObserver as the test said, there is no way to trigger #notify without listeners, so we can remove the whole test + code that relates to it --- packages/query-core/src/mutationObserver.ts | 15 ++++------ .../src/tests/mutationObserver.test.tsx | 30 ------------------- 2 files changed, 5 insertions(+), 40 deletions(-) diff --git a/packages/query-core/src/mutationObserver.ts b/packages/query-core/src/mutationObserver.ts index a3d140cc516..1c444550f50 100644 --- a/packages/query-core/src/mutationObserver.ts +++ b/packages/query-core/src/mutationObserver.ts @@ -18,7 +18,6 @@ type MutationObserverListener = ( ) => void interface NotifyOptions { - listeners?: boolean onError?: boolean onSuccess?: boolean } @@ -82,9 +81,7 @@ export class MutationObserver< this.#updateResult() // Determine which callbacks to trigger - const notifyOptions: NotifyOptions = { - listeners: true, - } + const notifyOptions: NotifyOptions = {} if (action.type === 'success') { notifyOptions.onSuccess = true @@ -107,7 +104,7 @@ export class MutationObserver< reset(): void { this.#currentMutation = undefined this.#updateResult() - this.#notify({ listeners: true }) + this.#notify({}) } mutate( @@ -193,11 +190,9 @@ export class MutationObserver< } // Then trigger the listeners - if (options.listeners) { - this.listeners.forEach((listener) => { - listener(this.#currentResult) - }) - } + this.listeners.forEach((listener) => { + listener(this.#currentResult) + }) }) } } diff --git a/packages/query-core/src/tests/mutationObserver.test.tsx b/packages/query-core/src/tests/mutationObserver.test.tsx index 12d1153ab66..1ca53454005 100644 --- a/packages/query-core/src/tests/mutationObserver.test.tsx +++ b/packages/query-core/src/tests/mutationObserver.test.tsx @@ -43,34 +43,4 @@ describe('mutationObserver', () => { // Clean-up unsubscribe2() }) - - test('should not notify listeners if options.listeners is set to false', async () => { - const mutation = new MutationObserver(queryClient, { - mutationFn: async (text: string) => { - await sleep(20) - return text - }, - }) - - const subscriptionHandler = jest.fn() - const unsubscribe = mutation.subscribe(subscriptionHandler) - mutation.mutate() - - await waitFor(() => { - // 2 calls: loading, success - expect(subscriptionHandler).toBeCalledTimes(2) - }) - subscriptionHandler.mockReset() - - // Force a notification with listeners set to false - // because there is no existing usage of notify with listeners set to false - mutation['notify']({ listeners: false }) - - await waitFor(() => { - // 0 call because no notification has been sent - expect(subscriptionHandler).toBeCalledTimes(0) - }) - - unsubscribe() - }) }) From 8b03b8608e782b0e8ee093a17d3bea197afcb98b Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Fri, 6 Jan 2023 20:39:14 +0100 Subject: [PATCH 10/60] refactor: mutation.setState as the tests says, it's unused, so we can remove it completely --- packages/query-core/src/mutation.ts | 15 ----------- packages/query-core/src/mutationCache.ts | 5 +--- packages/query-core/src/queryCache.ts | 5 +--- .../query-core/src/tests/mutations.test.tsx | 27 ------------------- 4 files changed, 2 insertions(+), 50 deletions(-) diff --git a/packages/query-core/src/mutation.ts b/packages/query-core/src/mutation.ts index b25793153e0..6dfb7225c64 100644 --- a/packages/query-core/src/mutation.ts +++ b/packages/query-core/src/mutation.ts @@ -66,18 +66,12 @@ interface ContinueAction { type: 'continue' } -interface SetStateAction { - type: 'setState' - state: MutationState -} - export type Action = | ContinueAction | ErrorAction | FailedAction | LoadingAction | PauseAction - | SetStateAction | SuccessAction // CLASS @@ -118,10 +112,6 @@ export class Mutation< return this.options.meta } - setState(state: MutationState): void { - this.#dispatch({ type: 'setState', state }) - } - addObserver(observer: MutationObserver): void { if (this.#observers.indexOf(observer) === -1) { this.#observers.push(observer) @@ -322,11 +312,6 @@ export class Mutation< isPaused: false, status: 'error', } - case 'setState': - return { - ...state, - ...action.state, - } } } this.state = reducer(this.state) diff --git a/packages/query-core/src/mutationCache.ts b/packages/query-core/src/mutationCache.ts index d8ea89ba31a..5e7e5e66179 100644 --- a/packages/query-core/src/mutationCache.ts +++ b/packages/query-core/src/mutationCache.ts @@ -75,14 +75,11 @@ type MutationCacheListener = (event: MutationCacheNotifyEvent) => void // CLASS export class MutationCache extends Subscribable { - config: MutationCacheConfig - #mutations: Mutation[] #mutationId: number - constructor(config?: MutationCacheConfig) { + constructor(public config: MutationCacheConfig = {}) { super() - this.config = config || {} this.#mutations = [] this.#mutationId = 0 } diff --git a/packages/query-core/src/queryCache.ts b/packages/query-core/src/queryCache.ts index e4c0ac71281..ed4e3a0a1c5 100644 --- a/packages/query-core/src/queryCache.ts +++ b/packages/query-core/src/queryCache.ts @@ -72,14 +72,11 @@ type QueryCacheListener = (event: QueryCacheNotifyEvent) => void // CLASS export class QueryCache extends Subscribable { - config: QueryCacheConfig - #queries: Query[] #queriesMap: QueryHashMap - constructor(config?: QueryCacheConfig) { + constructor(public config: QueryCacheConfig = {}) { super() - this.config = config || {} this.#queries = [] this.#queriesMap = {} } diff --git a/packages/query-core/src/tests/mutations.test.tsx b/packages/query-core/src/tests/mutations.test.tsx index 5eced09b45a..85c20b96c73 100644 --- a/packages/query-core/src/tests/mutations.test.tsx +++ b/packages/query-core/src/tests/mutations.test.tsx @@ -308,33 +308,6 @@ describe('mutations', () => { expect(onSettled).toHaveBeenCalled() }) - test('setState should update the mutation state', async () => { - const mutation = new MutationObserver(queryClient, { - mutationFn: async () => { - return 'update' - }, - onMutate: (text) => text, - }) - await mutation.mutate() - expect(mutation.getCurrentResult().data).toEqual('update') - - // Force setState usage - // because no use case has been found using mutation.setState - const currentMutation = mutation['currentMutation'] - currentMutation?.setState({ - context: undefined, - variables: undefined, - data: 'new', - error: undefined, - failureCount: 0, - failureReason: null, - isPaused: false, - status: 'success', - }) - - expect(mutation.getCurrentResult().data).toEqual('new') - }) - test('addObserver should not add an existing observer', async () => { const mutation = new MutationObserver(queryClient, { mutationFn: async () => { From 08005c1a592625c5fe0c193591b1c13a3677c144 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Fri, 6 Jan 2023 20:49:48 +0100 Subject: [PATCH 11/60] test(mutations): rewrite test to not rely on internals we can add the same observer twice and check that the observerAdded event has only been fired once --- .../query-core/src/tests/mutations.test.tsx | 27 ++++++++++--------- 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/packages/query-core/src/tests/mutations.test.tsx b/packages/query-core/src/tests/mutations.test.tsx index 85c20b96c73..adcfe0ec02d 100644 --- a/packages/query-core/src/tests/mutations.test.tsx +++ b/packages/query-core/src/tests/mutations.test.tsx @@ -2,6 +2,7 @@ import type { QueryClient } from '..' import { createQueryClient, executeMutation, queryKey, sleep } from './utils' import type { MutationState } from '../mutation' import { MutationObserver } from '../mutationObserver' +import { MutationCache } from '..' describe('mutations', () => { let queryClient: QueryClient @@ -309,21 +310,23 @@ describe('mutations', () => { }) test('addObserver should not add an existing observer', async () => { - const mutation = new MutationObserver(queryClient, { - mutationFn: async () => { - return 'update' - }, - onMutate: (text) => text, + const mutationCache = queryClient.getMutationCache() + const observer = new MutationObserver(queryClient, {}) + const currentMutation = mutationCache.build(queryClient, {}) + + const fn = jest.fn() + + const unsubscribe = mutationCache.subscribe((event) => { + fn(event.type) }) - await mutation.mutate() - // Force addObserver usage to add an existing observer - // because no use case has been found - const currentMutation = mutation['currentMutation']! - expect(currentMutation['observers'].length).toEqual(1) - currentMutation.addObserver(mutation) + currentMutation.addObserver(observer) + currentMutation.addObserver(observer) + + expect(fn).toHaveBeenCalledTimes(1) + expect(fn).toHaveBeenCalledWith('observerAdded') - expect(currentMutation['observers'].length).toEqual(1) + unsubscribe() }) test('mutate should throw an error if no mutationFn found', async () => { From 80c52520224f943062a83e1a2e27ac676af3df69 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Sat, 7 Jan 2023 10:52:22 +0100 Subject: [PATCH 12/60] tests: onlineManager fix onlineManager tests by not accessing private methods --- packages/query-core/src/tests/mutations.test.tsx | 1 - .../query-core/src/tests/onlineManager.test.tsx | 16 ++++++++++++---- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/packages/query-core/src/tests/mutations.test.tsx b/packages/query-core/src/tests/mutations.test.tsx index adcfe0ec02d..b281259f3e7 100644 --- a/packages/query-core/src/tests/mutations.test.tsx +++ b/packages/query-core/src/tests/mutations.test.tsx @@ -2,7 +2,6 @@ import type { QueryClient } from '..' import { createQueryClient, executeMutation, queryKey, sleep } from './utils' import type { MutationState } from '../mutation' import { MutationObserver } from '../mutationObserver' -import { MutationCache } from '..' describe('mutations', () => { let queryClient: QueryClient diff --git a/packages/query-core/src/tests/onlineManager.test.tsx b/packages/query-core/src/tests/onlineManager.test.tsx index c3a00e86d48..78cf9369774 100644 --- a/packages/query-core/src/tests/onlineManager.test.tsx +++ b/packages/query-core/src/tests/onlineManager.test.tsx @@ -56,26 +56,34 @@ describe('onlineManager', () => { expect(remove2Spy).not.toHaveBeenCalled() }) - test('cleanup should still be undefined if window is not defined', async () => { + test('cleanup (removeEventListener) should not be called if window is not defined', async () => { const restoreIsServer = setIsServer(true) + const removeEventListenerSpy = jest.spyOn(globalThis, 'removeEventListener') + const unsubscribe = onlineManager.subscribe(() => undefined) - expect(onlineManager['cleanup']).toBeUndefined() unsubscribe() + + expect(removeEventListenerSpy).not.toHaveBeenCalled() + restoreIsServer() }) - test('cleanup should still be undefined if window.addEventListener is not defined', async () => { + test('cleanup (removeEventListener) should not be called if window.addEventListener is not defined', async () => { const { addEventListener } = globalThis.window // @ts-expect-error globalThis.window.addEventListener = undefined + const removeEventListenerSpy = jest.spyOn(globalThis, 'removeEventListener') + const unsubscribe = onlineManager.subscribe(() => undefined) - expect(onlineManager['cleanup']).toBeUndefined() unsubscribe() + + expect(removeEventListenerSpy).not.toHaveBeenCalled() + globalThis.window.addEventListener = addEventListener }) From 3cb8103923f719a65bacd21b5156ee6c03aafef5 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Sat, 7 Jan 2023 10:54:44 +0100 Subject: [PATCH 13/60] tests: remove test for a case that cannot happen --- .../src/tests/queriesObserver.test.tsx | 35 ------------------- 1 file changed, 35 deletions(-) diff --git a/packages/query-core/src/tests/queriesObserver.test.tsx b/packages/query-core/src/tests/queriesObserver.test.tsx index e16c6d5de86..14754a8ba15 100644 --- a/packages/query-core/src/tests/queriesObserver.test.tsx +++ b/packages/query-core/src/tests/queriesObserver.test.tsx @@ -289,39 +289,4 @@ describe('queriesObserver', () => { // Clean-up unsubscribe2() }) - - test('onUpdate should not update the result for an unknown observer', async () => { - const key1 = queryKey() - const key2 = queryKey() - - const queriesObserver = new QueriesObserver(queryClient, [ - { - queryKey: key1, - queryFn: () => 1, - }, - ]) - - const newQueryObserver = new QueryObserver< - unknown, - unknown, - unknown, - unknown, - QueryKey - >(queryClient, { - queryKey: key2, - queryFn: () => 2, - }) - - // Force onUpdate with an unknown QueryObserver - // because no existing use case has been found in the lib - queriesObserver['onUpdate']( - newQueryObserver, - // The current queries observer result is re-used here - // to use a typescript friendly result - queriesObserver.getCurrentResult()[0]!, - ) - - // Should not alter the result - expect(queriesObserver.getCurrentResult()[-1]).toBeUndefined() - }) }) From 2ffc6c97c958c65ceedd11fde1b727cf7d90a146 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Sat, 7 Jan 2023 11:06:53 +0100 Subject: [PATCH 14/60] refactor(core): make initialState and revertState private they have not been accessed outside of query --- packages/query-core/src/query.ts | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/packages/query-core/src/query.ts b/packages/query-core/src/query.ts index 428da3a90f6..93e9e45a12f 100644 --- a/packages/query-core/src/query.ts +++ b/packages/query-core/src/query.ts @@ -147,11 +147,11 @@ export class Query< queryKey: TQueryKey queryHash: string options!: QueryOptions - initialState: QueryState - revertState?: QueryState state: QueryState isFetchingOptimistic?: boolean + #initialState: QueryState + #revertState?: QueryState #cache: QueryCache #logger: Logger #promise?: Promise @@ -171,8 +171,8 @@ export class Query< this.#logger = config.logger || defaultLogger this.queryKey = config.queryKey this.queryHash = config.queryHash - this.initialState = config.state || getDefaultState(this.options) - this.state = this.initialState + this.#initialState = config.state || getDefaultState(this.options) + this.state = this.#initialState } get meta(): QueryMeta | undefined { @@ -231,7 +231,7 @@ export class Query< reset(): void { this.destroy() - this.setState(this.initialState) + this.setState(this.#initialState) } isActive(): boolean { @@ -417,7 +417,7 @@ export class Query< ) // Store state in case the current fetch needs to be reverted - this.revertState = this.state + this.#revertState = this.state // Set to fetching state if not already in it if ( @@ -551,8 +551,8 @@ export class Query< case 'error': const error = action.error as unknown - if (isCancelledError(error) && error.revert && this.revertState) { - return { ...this.revertState } + if (isCancelledError(error) && error.revert && this.#revertState) { + return { ...this.#revertState } } return { From c49d66c1c21fc29faf8aaf8fb24d6be48b03d003 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Sat, 7 Jan 2023 11:11:50 +0100 Subject: [PATCH 15/60] tests: rewrite query tests to not depend on internals --- packages/query-core/src/tests/query.test.tsx | 109 ++++--------------- 1 file changed, 22 insertions(+), 87 deletions(-) diff --git a/packages/query-core/src/tests/query.test.tsx b/packages/query-core/src/tests/query.test.tsx index ca51051d7a5..858ebfdf830 100644 --- a/packages/query-core/src/tests/query.test.tsx +++ b/packages/query-core/src/tests/query.test.tsx @@ -700,7 +700,7 @@ describe('query', () => { notifySpy.mockRestore() }) - test('should not dispatch "invalidate" on invalidate() if already invalidated', async () => { + test('should not change state on invalidate() if already invalidated', async () => { const key = queryKey() await queryClient.prefetchQuery({ queryKey: key, queryFn: () => 'data' }) @@ -709,19 +709,14 @@ describe('query', () => { query.invalidate() expect(query.state.isInvalidated).toBeTruthy() - const dispatchOriginal = query['dispatch'] - const dispatchSpy = jest.fn() - query['dispatch'] = dispatchSpy + const previousState = query.state query.invalidate() - expect(query.state.isInvalidated).toBeTruthy() - expect(dispatchSpy).not.toHaveBeenCalled() - - query['dispatch'] = dispatchOriginal + expect(query.state).toBe(previousState) }) - test('fetch should not dispatch "fetch" if state meta and fetchOptions meta are the same object', async () => { + test('fetch should not dispatch "fetch" query is already fetching', async () => { const key = queryKey() const queryFn = async () => { @@ -729,50 +724,31 @@ describe('query', () => { return 'data' } + const updates: Array = [] + await queryClient.prefetchQuery({ queryKey: key, queryFn }) const query = queryCache.find({ queryKey: key })! - const meta = { meta1: '1' } - - // This first fetch will set the state.meta value - query.fetch( - { - queryKey: key, - queryFn, - }, - { - meta, - }, - ) - - // Spy on private dispatch method - const dispatchOriginal = query['dispatch'] - const dispatchSpy = jest.fn() - query['dispatch'] = dispatchSpy + const unsubscribe = queryClient.getQueryCache().subscribe((event) => { + updates.push(event.type) + }) - // Second fetch in parallel with the same meta - query.fetch( - { - queryKey: key, - queryFn, - }, - { - meta, - // cancelRefetch must be set to true to enter in the case to test - // where isFetching is true - cancelRefetch: true, - }, - ) + void query.fetch({ + queryKey: key, + queryFn, + }) - // Should not call dispatch with type set to fetch - expect(dispatchSpy).not.toHaveBeenCalledWith({ - meta, - type: 'fetch', + await query.fetch({ + queryKey: key, + queryFn, }) - // Clean-up - await sleep(20) - query['dispatch'] = dispatchOriginal + expect(updates).toEqual([ + 'updated', // type: 'fetch' + 'updated', // type: 'success' + ]) + + unsubscribe() }) test('fetch should not set the signal in the queryFnContext if AbortController is undefined', async () => { @@ -843,47 +819,6 @@ describe('query', () => { unsubscribe() }) - test('fetch should dispatch fetch if is fetching and current promise is undefined', async () => { - const key = queryKey() - - const queryFn = async () => { - await sleep(10) - return 'data' - } - - await queryClient.prefetchQuery({ queryKey: key, queryFn }) - const query = queryCache.find({ queryKey: key })! - - query.fetch({ - queryKey: key, - queryFn, - }) - - // Force promise to undefined - // because no use case have been identified - query['promise'] = undefined - - // Spy on private dispatch method - const dispatchOriginal = query['dispatch'] - const dispatchSpy = jest.fn() - query['dispatch'] = dispatchSpy - - query.fetch({ - queryKey: key, - queryFn, - }) - - // Should call dispatch with type set to fetch - expect(dispatchSpy).toHaveBeenCalledWith({ - meta: undefined, - type: 'fetch', - }) - - // Clean-up - await sleep(20) - query['dispatch'] = dispatchOriginal - }) - test('constructor should call initialDataUpdatedAt if defined as a function', async () => { const key = queryKey() From cac35bce2b1722c4536c17abd954acbce8bea3f1 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Sat, 7 Jan 2023 11:15:59 +0100 Subject: [PATCH 16/60] tests: rewrite queryCache tests to not depend on internals --- .../query-core/src/tests/queryCache.test.tsx | 33 ++----------------- 1 file changed, 2 insertions(+), 31 deletions(-) diff --git a/packages/query-core/src/tests/queryCache.test.tsx b/packages/query-core/src/tests/queryCache.test.tsx index c7ae5bfdab2..6c4ca43cdb9 100644 --- a/packages/query-core/src/tests/queryCache.test.tsx +++ b/packages/query-core/src/tests/queryCache.test.tsx @@ -1,7 +1,6 @@ import { sleep, queryKey, createQueryClient } from './utils' import type { QueryClient } from '..' import { QueryCache, QueryObserver } from '..' -import type { Query } from '.././query' import { waitFor } from '@testing-library/react' describe('queryCache', () => { @@ -280,42 +279,14 @@ describe('queryCache', () => { describe('QueryCache.add', () => { test('should not try to add a query already added to the cache', async () => { const key = queryKey() - const hash = `["${key}"]` await queryClient.prefetchQuery({ queryKey: key, queryFn: () => 'data1' }) - // Directly add the query from the cache - // to simulate a race condition - const query = queryCache['queriesMap'][hash] as Query + const query = queryCache.findAll()[0]! const queryClone = Object.assign({}, query) - // No error should be thrown when trying to add the query queryCache.add(queryClone) - expect(queryCache['queries'].length).toEqual(1) - - // Clean-up to avoid an error when queryClient.clear() - delete queryCache['queriesMap'][hash] - }) - - describe('QueryCache.remove', () => { - test('should not try to remove a query already removed from the cache', async () => { - const key = queryKey() - const hash = `["${key}"]` - - await queryClient.prefetchQuery({ - queryKey: key, - queryFn: () => 'data1', - }) - - // Directly remove the query from the cache - // to simulate a race condition - const query = queryCache['queriesMap'][hash] as Query - const queryClone = Object.assign({}, query) - delete queryCache['queriesMap'][hash] - - // No error should be thrown when trying to remove the query - expect(() => queryCache.remove(queryClone)).not.toThrow() - }) + expect(queryCache.getAll().length).toEqual(1) }) }) }) From 29064699744dab0e14b7842539ae08b59f91d1c3 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Sat, 7 Jan 2023 11:19:02 +0100 Subject: [PATCH 17/60] refactor: notifyOptions.cache it was always set to true - there is no way to _not_ notify the cache --- packages/query-core/src/queryObserver.ts | 13 +++++------- .../src/tests/queryObserver.test.tsx | 21 ------------------- 2 files changed, 5 insertions(+), 29 deletions(-) diff --git a/packages/query-core/src/queryObserver.ts b/packages/query-core/src/queryObserver.ts index 462c7d64281..b4521afccd7 100644 --- a/packages/query-core/src/queryObserver.ts +++ b/packages/query-core/src/queryObserver.ts @@ -28,7 +28,6 @@ type QueryObserverListener = ( ) => void export interface NotifyOptions { - cache?: boolean listeners?: boolean onError?: boolean onSuccess?: boolean @@ -591,7 +590,7 @@ export class QueryObserver< this.#currentResult = nextResult // Determine which callbacks to trigger - const defaultNotifyOptions: NotifyOptions = { cache: true } + const defaultNotifyOptions: NotifyOptions = {} const shouldNotifyListeners = (): boolean => { if (!prevResult) { @@ -682,12 +681,10 @@ export class QueryObserver< } // Then the cache listeners - if (notifyOptions.cache) { - this.#client.getQueryCache().notify({ - query: this.#currentQuery, - type: 'observerResultsUpdated', - }) - } + this.#client.getQueryCache().notify({ + query: this.#currentQuery, + type: 'observerResultsUpdated', + }) }) } } diff --git a/packages/query-core/src/tests/queryObserver.test.tsx b/packages/query-core/src/tests/queryObserver.test.tsx index 5e30ff04311..de234832d79 100644 --- a/packages/query-core/src/tests/queryObserver.test.tsx +++ b/packages/query-core/src/tests/queryObserver.test.tsx @@ -737,27 +737,6 @@ describe('queryObserver', () => { expect(observer.getCurrentResult().isPlaceholderData).toBe(false) }) - test('updateResult should not notify cache listeners if cache option is false', async () => { - const key = queryKey() - - const data1 = { value: 'data 1' } - const data2 = { value: 'data 2' } - - await queryClient.prefetchQuery({ queryKey: key, queryFn: () => data1 }) - const observer = new QueryObserver(queryClient, { - queryKey: key, - }) - await queryClient.prefetchQuery({ queryKey: key, queryFn: () => data2 }) - - const spy = jest.fn() - const unsubscribe = queryClient.getQueryCache().subscribe(spy) - observer.updateResult({ cache: false }) - - expect(spy).toHaveBeenCalledTimes(0) - - unsubscribe() - }) - test('should not notify observer when the stale timeout expires and the current result is stale', async () => { const key = queryKey() const queryFn = () => 'data' From 31252c5a33e9e8ff1b5c4d337d4158cd8db30eba Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Sat, 7 Jan 2023 11:23:38 +0100 Subject: [PATCH 18/60] chore: remove unused imports --- packages/query-core/src/tests/queriesObserver.test.tsx | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/query-core/src/tests/queriesObserver.test.tsx b/packages/query-core/src/tests/queriesObserver.test.tsx index 14754a8ba15..32487cd253c 100644 --- a/packages/query-core/src/tests/queriesObserver.test.tsx +++ b/packages/query-core/src/tests/queriesObserver.test.tsx @@ -1,8 +1,7 @@ import { waitFor } from '@testing-library/react' import { sleep, queryKey, createQueryClient, mockLogger } from './utils' import type { QueryClient, QueryObserverResult } from '..' -import { QueriesObserver, QueryObserver } from '..' -import type { QueryKey } from '..' +import { QueriesObserver } from '..' describe('queriesObserver', () => { let queryClient: QueryClient From 552ee301f96991edecb3e54abb93fe7eb74cd0a8 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Sat, 7 Jan 2023 11:31:23 +0100 Subject: [PATCH 19/60] refactor: unify partialMatchKey and partialDeepEqual --- packages/query-core/src/tests/utils.test.tsx | 42 ++++++++++---------- packages/query-core/src/utils.ts | 12 ++---- 2 files changed, 24 insertions(+), 30 deletions(-) diff --git a/packages/query-core/src/tests/utils.test.tsx b/packages/query-core/src/tests/utils.test.tsx index 8deefe47b5f..104416bee87 100644 --- a/packages/query-core/src/tests/utils.test.tsx +++ b/packages/query-core/src/tests/utils.test.tsx @@ -1,6 +1,6 @@ import { replaceEqualDeep, - partialDeepEqual, + partialMatchKey, isPlainObject, matchMutation, scheduleMicrotask, @@ -66,47 +66,47 @@ describe('core/utils', () => { }) }) - describe('partialDeepEqual', () => { + describe('partialMatchKey', () => { it('should return `true` if a includes b', () => { - const a = { a: { b: 'b' }, c: 'c', d: [{ d: 'd ' }] } - const b = { a: { b: 'b' }, c: 'c', d: [] } - expect(partialDeepEqual(a, b)).toEqual(true) + const a = [{ a: { b: 'b' }, c: 'c', d: [{ d: 'd ' }] }] + const b = [{ a: { b: 'b' }, c: 'c', d: [] }] + expect(partialMatchKey(a, b)).toEqual(true) }) it('should return `false` if a does not include b', () => { - const a = { a: { b: 'b' }, c: 'c', d: [] } - const b = { a: { b: 'b' }, c: 'c', d: [{ d: 'd ' }] } - expect(partialDeepEqual(a, b)).toEqual(false) + const a = [{ a: { b: 'b' }, c: 'c', d: [] }] + const b = [{ a: { b: 'b' }, c: 'c', d: [{ d: 'd ' }] }] + expect(partialMatchKey(a, b)).toEqual(false) }) it('should return `true` if array a includes array b', () => { const a = [1, 2, 3] const b = [1, 2] - expect(partialDeepEqual(a, b)).toEqual(true) + expect(partialMatchKey(a, b)).toEqual(true) }) it('should return `false` if a is null and b is not', () => { - const a = null - const b = { a: { b: 'b' }, c: 'c', d: [{ d: 'd ' }] } - expect(partialDeepEqual(a, b)).toEqual(false) + const a = [null] + const b = [{ a: { b: 'b' }, c: 'c', d: [{ d: 'd ' }] }] + expect(partialMatchKey(a, b)).toEqual(false) }) it('should return `false` if a contains null and b is not', () => { - const a = { a: null, c: 'c', d: [] } - const b = { a: { b: 'b' }, c: 'c', d: [{ d: 'd ' }] } - expect(partialDeepEqual(a, b)).toEqual(false) + const a = [{ a: null, c: 'c', d: [] }] + const b = [{ a: { b: 'b' }, c: 'c', d: [{ d: 'd ' }] }] + expect(partialMatchKey(a, b)).toEqual(false) }) it('should return `false` if b is null and a is not', () => { - const a = { a: { b: 'b' }, c: 'c', d: [] } - const b = null - expect(partialDeepEqual(a, b)).toEqual(false) + const a = [{ a: { b: 'b' }, c: 'c', d: [] }] + const b = [null] + expect(partialMatchKey(a, b)).toEqual(false) }) it('should return `false` if b contains null and a is not', () => { - const a = { a: { b: 'b' }, c: 'c', d: [] } - const b = { a: null, c: 'c', d: [{ d: 'd ' }] } - expect(partialDeepEqual(a, b)).toEqual(false) + const a = [{ a: { b: 'b' }, c: 'c', d: [] }] + const b = [{ a: null, c: 'c', d: [{ d: 'd ' }] }] + expect(partialMatchKey(a, b)).toEqual(false) }) }) diff --git a/packages/query-core/src/utils.ts b/packages/query-core/src/utils.ts index e58f586e153..5e80f046a7e 100644 --- a/packages/query-core/src/utils.ts +++ b/packages/query-core/src/utils.ts @@ -196,14 +196,8 @@ export function hashQueryKey(queryKey: QueryKey): string { /** * Checks if key `b` partially matches with key `a`. */ -export function partialMatchKey(a: QueryKey, b: QueryKey): boolean { - return partialDeepEqual(a, b) -} - -/** - * Checks if `b` partially matches with `a`. - */ -export function partialDeepEqual(a: any, b: any): boolean { +export function partialMatchKey(a: QueryKey, b: QueryKey): boolean +export function partialMatchKey(a: any, b: any): boolean { if (a === b) { return true } @@ -213,7 +207,7 @@ export function partialDeepEqual(a: any, b: any): boolean { } if (a && b && typeof a === 'object' && typeof b === 'object') { - return !Object.keys(b).some((key) => !partialDeepEqual(a[key], b[key])) + return !Object.keys(b).some((key) => !partialMatchKey(a[key], b[key])) } return false From a4bba9eb64e2ea0ba719dc78bb9b5264c5941a26 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Sat, 7 Jan 2023 11:33:05 +0100 Subject: [PATCH 20/60] refactor: remove Array check when checking for keys during filtering a simple truthy check suffices, as we can only pass an Array or undefined in here --- packages/query-core/src/utils.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/query-core/src/utils.ts b/packages/query-core/src/utils.ts index 5e80f046a7e..823e4afd9a2 100644 --- a/packages/query-core/src/utils.ts +++ b/packages/query-core/src/utils.ts @@ -96,7 +96,7 @@ export function matchQuery( stale, } = filters - if (Array.isArray(queryKey)) { + if (queryKey) { if (exact) { if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) { return false @@ -139,7 +139,7 @@ export function matchMutation( mutation: Mutation, ): boolean { const { exact, fetching, predicate, mutationKey } = filters - if (Array.isArray(mutationKey)) { + if (mutationKey) { if (!mutation.options.mutationKey) { return false } From c4a2eb83ec11ca5fb410bb69d215739f2456c905 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Sat, 7 Jan 2023 11:35:14 +0100 Subject: [PATCH 21/60] refactor: rename hashQueryKey to hashKey because we also use it for mutationKeys --- packages/query-core/src/index.ts | 2 +- packages/query-core/src/queryClient.ts | 6 +++--- packages/query-core/src/utils.ts | 10 ++++------ 3 files changed, 8 insertions(+), 10 deletions(-) diff --git a/packages/query-core/src/index.ts b/packages/query-core/src/index.ts index 241dd8f615d..ffee373668b 100644 --- a/packages/query-core/src/index.ts +++ b/packages/query-core/src/index.ts @@ -11,7 +11,7 @@ export { MutationObserver } from './mutationObserver' export { notifyManager } from './notifyManager' export { focusManager } from './focusManager' export { onlineManager } from './onlineManager' -export { hashQueryKey, replaceEqualDeep, isServer } from './utils' +export { hashKey, replaceEqualDeep, isServer } from './utils' export type { MutationFilters, QueryFilters, Updater } from './utils' export { isCancelledError } from './retryer' export { dehydrate, hydrate } from './hydration' diff --git a/packages/query-core/src/queryClient.ts b/packages/query-core/src/queryClient.ts index 9e7062511ba..75df109c662 100644 --- a/packages/query-core/src/queryClient.ts +++ b/packages/query-core/src/queryClient.ts @@ -1,6 +1,6 @@ import type { QueryFilters, Updater, MutationFilters } from './utils' import { - hashQueryKey, + hashKey, noop, partialMatchKey, hashQueryKeyByOptions, @@ -369,7 +369,7 @@ export class QueryClient { options: Omit, 'queryKey'>, ): void { const result = this.#queryDefaults.find( - (x) => hashQueryKey(queryKey) === hashQueryKey(x.queryKey), + (x) => hashKey(queryKey) === hashKey(x.queryKey), ) if (result) { result.defaultOptions = options @@ -414,7 +414,7 @@ export class QueryClient { options: MutationObserverOptions, ): void { const result = this.#mutationDefaults.find( - (x) => hashQueryKey(mutationKey) === hashQueryKey(x.mutationKey), + (x) => hashKey(mutationKey) === hashKey(x.mutationKey), ) if (result) { result.defaultOptions = options diff --git a/packages/query-core/src/utils.ts b/packages/query-core/src/utils.ts index 823e4afd9a2..df97e95daa8 100644 --- a/packages/query-core/src/utils.ts +++ b/packages/query-core/src/utils.ts @@ -144,9 +144,7 @@ export function matchMutation( return false } if (exact) { - if ( - hashQueryKey(mutation.options.mutationKey) !== hashQueryKey(mutationKey) - ) { + if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) { return false } } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) { @@ -172,15 +170,15 @@ export function hashQueryKeyByOptions( queryKey: TQueryKey, options?: QueryOptions, ): string { - const hashFn = options?.queryKeyHashFn || hashQueryKey + const hashFn = options?.queryKeyHashFn || hashKey return hashFn(queryKey) } /** - * Default query keys hash function. + * Default query & mutation keys hash function. * Hashes the value into a stable hash. */ -export function hashQueryKey(queryKey: QueryKey): string { +export function hashKey(queryKey: QueryKey | MutationKey): string { return JSON.stringify(queryKey, (_, val) => isPlainObject(val) ? Object.keys(val) From aa7a3fe100135301c43f257823a94399557d3994 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Sat, 7 Jan 2023 11:40:03 +0100 Subject: [PATCH 22/60] tests: remove unnecessary condition signal is now always defined --- packages/query-core/src/tests/queryClient.test.tsx | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/packages/query-core/src/tests/queryClient.test.tsx b/packages/query-core/src/tests/queryClient.test.tsx index 76a7e8612f2..0dca06295a9 100644 --- a/packages/query-core/src/tests/queryClient.test.tsx +++ b/packages/query-core/src/tests/queryClient.test.tsx @@ -1239,9 +1239,7 @@ describe('queryClient', () => { return new Promise((resolve) => { fetchCount++ setTimeout(() => resolve(5), 10) - if (signal) { - signal.addEventListener('abort', abortFn) - } + signal.addEventListener('abort', abortFn) }) }, initialData: 1, @@ -1264,9 +1262,7 @@ describe('queryClient', () => { return new Promise((resolve) => { fetchCount++ setTimeout(() => resolve(5), 10) - if (signal) { - signal.addEventListener('abort', abortFn) - } + signal.addEventListener('abort', abortFn) }) }, initialData: 1, From ac8184c006b1206224c1c9ebb7fe7b919c597692 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Sat, 7 Jan 2023 11:46:00 +0100 Subject: [PATCH 23/60] tests: get rid of annoying false-positive console.error log --- .../react-query-devtools/src/__tests__/Explorer.test.tsx | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/packages/react-query-devtools/src/__tests__/Explorer.test.tsx b/packages/react-query-devtools/src/__tests__/Explorer.test.tsx index 7d4dd7e00e1..c566950d2e2 100644 --- a/packages/react-query-devtools/src/__tests__/Explorer.test.tsx +++ b/packages/react-query-devtools/src/__tests__/Explorer.test.tsx @@ -90,6 +90,9 @@ describe('Explorer', () => { }) it('when the copy button is clicked but there is an error, show error state', async () => { + const consoleMock = jest.spyOn(console, 'error') + consoleMock.mockImplementation(() => undefined) + // Mock clipboard with error state Object.defineProperty(navigator, 'clipboard', { value: { @@ -117,6 +120,8 @@ describe('Explorer', () => { // Check that it has failed await screen.findByLabelText('Failed copying to clipboard') + expect(consoleMock).toHaveBeenCalledTimes(1) + consoleMock.mockRestore() }) }) From 4968b1ef653469e94fdaadb4a6d6fd5b84a52174 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Sat, 7 Jan 2023 11:58:56 +0100 Subject: [PATCH 24/60] tests: don't rely on internals re-wrote some tests and removed some others that weren't easily testable without relying on internals --- packages/query-core/src/tests/query.test.tsx | 24 ----------- .../src/tests/queryObserver.test.tsx | 43 +++++-------------- .../src/__tests__/suspense.test.tsx | 5 --- .../src/__tests__/suspense.test.tsx | 5 --- 4 files changed, 10 insertions(+), 67 deletions(-) diff --git a/packages/query-core/src/tests/query.test.tsx b/packages/query-core/src/tests/query.test.tsx index 858ebfdf830..f6aeac4def4 100644 --- a/packages/query-core/src/tests/query.test.tsx +++ b/packages/query-core/src/tests/query.test.tsx @@ -751,30 +751,6 @@ describe('query', () => { unsubscribe() }) - test('fetch should not set the signal in the queryFnContext if AbortController is undefined', async () => { - const key = queryKey() - - // Mock the AbortController to be undefined - const AbortControllerOriginal = globalThis['AbortController'] - //@ts-expect-error - globalThis['AbortController'] = undefined - - let signalTest: any - await queryClient.prefetchQuery({ - queryKey: key, - queryFn: ({ signal }) => { - signalTest = signal - return 'data' - }, - }) - - expect(signalTest).toBeUndefined() - - // Clean-up - //@ts-ignore - globalThis['AbortController'] = AbortControllerOriginal - }) - test('fetch should throw an error if the queryFn is not defined', async () => { const key = queryKey() diff --git a/packages/query-core/src/tests/queryObserver.test.tsx b/packages/query-core/src/tests/queryObserver.test.tsx index de234832d79..a0d835c0861 100644 --- a/packages/query-core/src/tests/queryObserver.test.tsx +++ b/packages/query-core/src/tests/queryObserver.test.tsx @@ -460,22 +460,26 @@ describe('queryObserver', () => { test('should clear interval when unsubscribing to a refetchInterval query', async () => { const key = queryKey() + let count = 0 - const fetchData = () => Promise.resolve('data') + const fetchData = () => { + count++ + Promise.resolve('data') + } const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: fetchData, cacheTime: 0, - refetchInterval: 1, + refetchInterval: 10, }) const unsubscribe = observer.subscribe(() => undefined) - // @ts-expect-error - expect(observer.refetchIntervalId).not.toBeUndefined() + expect(count).toBe(1) + await sleep(15) + expect(count).toBe(2) unsubscribe() - // @ts-expect-error - expect(observer.refetchIntervalId).toBeUndefined() await sleep(10) expect(queryClient.getQueryCache().find({ queryKey: key })).toBeUndefined() + expect(count).toBe(2) }) test('uses placeholderData as non-cache data when loading a query with no data', async () => { @@ -737,33 +741,6 @@ describe('queryObserver', () => { expect(observer.getCurrentResult().isPlaceholderData).toBe(false) }) - test('should not notify observer when the stale timeout expires and the current result is stale', async () => { - const key = queryKey() - const queryFn = () => 'data' - - await queryClient.prefetchQuery({ queryKey: key, queryFn }) - const observer = new QueryObserver(queryClient, { - queryKey: key, - queryFn, - staleTime: 20, - }) - - const spy = jest.fn() - const unsubscribe = observer.subscribe(spy) - await queryClient.refetchQueries({ queryKey: key }) - await sleep(10) - - // Force isStale to true - // because no use case has been found to reproduce this condition - // @ts-ignore - observer['currentResult'].isStale = true - spy.mockReset() - await sleep(30) - expect(spy).not.toHaveBeenCalled() - - unsubscribe() - }) - test('setOptions should notify cache listeners', async () => { const key = queryKey() diff --git a/packages/react-query/src/__tests__/suspense.test.tsx b/packages/react-query/src/__tests__/suspense.test.tsx index 73515801a6e..56de3d8df60 100644 --- a/packages/react-query/src/__tests__/suspense.test.tsx +++ b/packages/react-query/src/__tests__/suspense.test.tsx @@ -493,11 +493,6 @@ describe("useQuery's in Suspense mode", () => { fireEvent.click(rendered.getByText('switch')) await waitFor(() => rendered.getByText('Loading...')) await waitFor(() => rendered.getByText(`data: ${key2}`)) - expect( - // @ts-expect-error - queryClient.getQueryCache().find({ queryKey: key2 })!.observers[0] - .listeners.length, - ).toBe(1) }) it('should retry fetch if the reset error boundary has been reset with global hook', async () => { diff --git a/packages/solid-query/src/__tests__/suspense.test.tsx b/packages/solid-query/src/__tests__/suspense.test.tsx index d9b3d588a63..e55509652a3 100644 --- a/packages/solid-query/src/__tests__/suspense.test.tsx +++ b/packages/solid-query/src/__tests__/suspense.test.tsx @@ -526,11 +526,6 @@ describe("useQuery's in Suspense mode", () => { fireEvent.click(screen.getByText('switch')) await waitFor(() => screen.getByText('Loading...')) await waitFor(() => screen.getByText(`data: ${key2}`)) - expect( - // @ts-expect-error - queryClient.getQueryCache().find({ queryKey: key2 })!.observers[0] - .listeners.length, - ).toBe(1) }) it('should throw errors to the error boundary by default', async () => { From 5a8b3687f7a795d22d1fc94a880769364044ebed Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Sat, 7 Jan 2023 12:03:57 +0100 Subject: [PATCH 25/60] docs: document size improvements --- docs/react/guides/migrating-to-react-query-5.md | 11 +++++++++-- docs/react/installation.md | 12 ++++++------ 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/docs/react/guides/migrating-to-react-query-5.md b/docs/react/guides/migrating-to-react-query-5.md index c068c1cd9ab..51d1c54c219 100644 --- a/docs/react/guides/migrating-to-react-query-5.md +++ b/docs/react/guides/migrating-to-react-query-5.md @@ -9,7 +9,7 @@ v5 is a major version, so there are some breaking changes to be aware of: ### Supports a single signature, one object -useQuery and friends used to have many overloads in TypeScript - different ways how the function can be invoked. Not only this was tough to maintain, type wise, it also required a runtime check to see which type the first and the second parameter, to correctly create options. +useQuery and friends used to have many overloads in TypeScript - different ways how the function can be invoked. Not only this was tough to maintain, type wise, it also required a runtime check to see which type the first and the second parameter, to correctly create options. now we only support the object format. @@ -117,7 +117,6 @@ if you still need to remove a query, you can use `queryClient.removeQueries({que Mainly because an important fix was shipped around type inference. Please see this [TypeScript issue](https://github.com/microsoft/TypeScript/issues/43371) for more information. - ### The `isDataEqual` options has been removed from useQuery Previously, This function was used to indicate whether to use previous `data` (`true`) or new data (`false`) as a resolved data for the query. @@ -131,6 +130,14 @@ You can achieve the same functionality by passing a function to `structuralShari + structuralSharing: (oldData, newData) => customCheck(oldData, newData) ? oldData : replaceEqualDeep(oldData, newData) ``` +### Supported Browsers + +We have updated our browserslist to produce a more modern, performant and smaller bundle. You can read about the requirements [here](../installation#requirements). + +### Private class fields and methods + +TanStack Query has always had private fields and methods on classes, but they weren't really private - they were just private in `TypeScript`. We now use [ECMAScript Private class features](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields), which means those fields are now truly private and can't be accessed from the outside at runtime. + ### The `useErrorBoundary` prop has been renamed to `throwErrors` To make the `useErrorBoundary` prop more framework-agnostic and avoid confusion with the established React function prefix "`use`" for hooks and the "ErrorBoundary" component name, it has been renamed to `throwErrors` to more accurately reflect its functionality. diff --git a/docs/react/installation.md b/docs/react/installation.md index b59a58e246f..6d212e0c7ee 100644 --- a/docs/react/installation.md +++ b/docs/react/installation.md @@ -38,12 +38,12 @@ Once you've added this you will have access to the `window.ReactQuery` object an React Query is optimized for modern browsers. It is compatible with the following browsers config ``` -Chrome >= 73 -Firefox >= 78 -Edge >= 79 -Safari >= 12.0 -iOS >= 12.0 -opera >= 53 +Chrome >= 84 +Firefox >= 90 +Edge >= 84 +Safari >= 15 +iOS >= 15 +opera >= 70 ``` > Depending on your environment, you might need to add polyfills. If you want to support older browsers, you need to transpile the library from `node_modules` yourselves. From 5a309d3715bf7c87143b9b8445baddb342c209db Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Sat, 7 Jan 2023 12:04:53 +0100 Subject: [PATCH 26/60] tests: fix copyButton test --- packages/react-query-devtools/src/__tests__/Explorer.test.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/react-query-devtools/src/__tests__/Explorer.test.tsx b/packages/react-query-devtools/src/__tests__/Explorer.test.tsx index c566950d2e2..cf5e15443cf 100644 --- a/packages/react-query-devtools/src/__tests__/Explorer.test.tsx +++ b/packages/react-query-devtools/src/__tests__/Explorer.test.tsx @@ -120,7 +120,7 @@ describe('Explorer', () => { // Check that it has failed await screen.findByLabelText('Failed copying to clipboard') - expect(consoleMock).toHaveBeenCalledTimes(1) + expect(consoleMock).toHaveBeenCalled() consoleMock.mockRestore() }) }) From f0688940481208a894bf1db62a4461c21af60970 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Wed, 11 Jan 2023 17:22:29 +0100 Subject: [PATCH 27/60] feat: reset mutation variables in success / error case - remove undocumented variables option in MutationOptions and pass variables via `execute` method instead - reset mutation variables to allow for ui-based optimistic updates - get rid of notifyOptions by just forwarding the whole action - the options were a wrapper that turned action with a discriminated union into two booleans, which doesn't make much sense as you can only ever be in one of the states --- packages/query-core/src/mutation.ts | 58 +++--- packages/query-core/src/mutationObserver.ts | 69 ++----- .../query-core/src/tests/hydration.test.tsx | 33 +-- .../src/tests/mutationCache.test.tsx | 191 +++++++++++------- .../query-core/src/tests/mutations.test.tsx | 40 ++-- packages/query-core/src/tests/utils.ts | 18 +- packages/query-core/src/types.ts | 5 +- .../src/__tests__/persist.test.ts | 1 - .../src/__tests__/useMutation.test.tsx | 47 ++++- 9 files changed, 252 insertions(+), 210 deletions(-) diff --git a/packages/query-core/src/mutation.ts b/packages/query-core/src/mutation.ts index 6dfb7225c64..dda7ebbb4ab 100644 --- a/packages/query-core/src/mutation.ts +++ b/packages/query-core/src/mutation.ts @@ -48,14 +48,16 @@ interface LoadingAction { context?: TContext } -interface SuccessAction { +interface SuccessAction { type: 'success' data: TData + variables: TVariables } -interface ErrorAction { +interface ErrorAction { type: 'error' error: TError + variables: TVariables } interface PauseAction { @@ -68,11 +70,11 @@ interface ContinueAction { export type Action = | ContinueAction - | ErrorAction + | ErrorAction | FailedAction | LoadingAction | PauseAction - | SuccessAction + | SuccessAction // CLASS @@ -157,7 +159,7 @@ export class Mutation< return this.execute() } - async execute(): Promise { + async execute(input?: TVariables): Promise { const executeMutation = () => { this.#retryer = createRetryer({ fn: () => { @@ -184,54 +186,52 @@ export class Mutation< } const restored = this.state.status === 'loading' + let variables: TVariables | undefined = input + try { if (!restored) { - this.#dispatch({ type: 'loading', variables: this.options.variables! }) + this.#dispatch({ type: 'loading', variables }) // Notify cache callback await this.#mutationCache.config.onMutate?.( - this.state.variables, + variables, this as Mutation, ) - const context = await this.options.onMutate?.(this.state.variables!) + const context = await this.options.onMutate?.(variables!) if (context !== this.state.context) { this.#dispatch({ type: 'loading', context, - variables: this.state.variables, + variables, }) } } + // this makes sure variables are set even if the mutation is restored + // in which case we call execute without input + // we need to store variables here because dispatching success or error + // will reset the variables to undefined and then onSuccess and other callbacks won't see them + variables = this.state.variables const data = await executeMutation() // Notify cache callback await this.#mutationCache.config.onSuccess?.( data, - this.state.variables, + variables, this.state.context, this as Mutation, ) - await this.options.onSuccess?.( - data, - this.state.variables!, - this.state.context!, - ) + await this.options.onSuccess?.(data, variables!, this.state.context!) - await this.options.onSettled?.( - data, - null, - this.state.variables!, - this.state.context, - ) + await this.options.onSettled?.(data, null, variables!, this.state.context) - this.#dispatch({ type: 'success', data }) + this.#dispatch({ type: 'success', data, variables: variables! }) return data } catch (error) { try { // Notify cache callback await this.#mutationCache.config.onError?.( error, - this.state.variables, + variables, this.state.context, this as Mutation, ) @@ -242,19 +242,23 @@ export class Mutation< await this.options.onError?.( error as TError, - this.state.variables!, + variables!, this.state.context, ) await this.options.onSettled?.( undefined, error as TError, - this.state.variables!, + variables!, this.state.context, ) throw error } finally { - this.#dispatch({ type: 'error', error: error as TError }) + this.#dispatch({ + type: 'error', + error: error as TError, + variables: variables!, + }) } } } @@ -301,6 +305,7 @@ export class Mutation< error: null, status: 'success', isPaused: false, + variables: undefined, } case 'error': return { @@ -311,6 +316,7 @@ export class Mutation< failureReason: action.error, isPaused: false, status: 'error', + variables: undefined, } } } diff --git a/packages/query-core/src/mutationObserver.ts b/packages/query-core/src/mutationObserver.ts index 1c444550f50..3910a4c7fe4 100644 --- a/packages/query-core/src/mutationObserver.ts +++ b/packages/query-core/src/mutationObserver.ts @@ -5,7 +5,6 @@ import type { QueryClient } from './queryClient' import { Subscribable } from './subscribable' import type { MutateOptions, - MutationObserverBaseResult, MutationObserverResult, MutationObserverOptions, } from './types' @@ -17,11 +16,6 @@ type MutationObserverListener = ( result: MutationObserverResult, ) => void -interface NotifyOptions { - onError?: boolean - onSuccess?: boolean -} - // CLASS export class MutationObserver< @@ -80,16 +74,7 @@ export class MutationObserver< onMutationUpdate(action: Action): void { this.#updateResult() - // Determine which callbacks to trigger - const notifyOptions: NotifyOptions = {} - - if (action.type === 'success') { - notifyOptions.onSuccess = true - } else if (action.type === 'error') { - notifyOptions.onError = true - } - - this.#notify(notifyOptions) + this.#notify(action) } getCurrentResult(): MutationObserverResult< @@ -104,7 +89,7 @@ export class MutationObserver< reset(): void { this.#currentMutation = undefined this.#updateResult() - this.#notify({}) + this.#notify() } mutate( @@ -121,26 +106,19 @@ export class MutationObserver< .getMutationCache() .build(this.#client, { ...this.options, - variables: - typeof variables !== 'undefined' ? variables : this.options.variables, }) this.#currentMutation.addObserver(this) - return this.#currentMutation.execute() + return this.#currentMutation.execute(variables) } #updateResult(): void { - const state = this.#currentMutation - ? this.#currentMutation.state - : getDefaultState() - - const result: MutationObserverBaseResult< - TData, - TError, - TVariables, - TContext - > = { + const state = + this.#currentMutation?.state ?? + getDefaultState() + + this.#currentResult = { ...state, isLoading: state.status === 'loading', isSuccess: state.status === 'success', @@ -148,42 +126,35 @@ export class MutationObserver< isIdle: state.status === 'idle', mutate: this.mutate, reset: this.reset, - } - - this.#currentResult = result as MutationObserverResult< - TData, - TError, - TVariables, - TContext - > + } as MutationObserverResult } - #notify(options: NotifyOptions) { + #notify(action?: Action): void { notifyManager.batch(() => { // First trigger the mutate callbacks if (this.#mutateOptions) { - if (options.onSuccess) { + if (action?.type === 'success') { this.#mutateOptions.onSuccess?.( - this.#currentResult.data!, - this.#currentResult.variables!, + action.data, + action.variables, this.#currentResult.context!, ) this.#mutateOptions.onSettled?.( - this.#currentResult.data!, + action.data, null, - this.#currentResult.variables!, + action.variables, this.#currentResult.context, ) - } else if (options.onError) { + } else if (action?.type === 'error') { this.#mutateOptions.onError?.( - this.#currentResult.error!, - this.#currentResult.variables!, + action.error, + action.variables, this.#currentResult.context, ) this.#mutateOptions.onSettled?.( undefined, - this.#currentResult.error, - this.#currentResult.variables!, + action.error, + action.variables, this.#currentResult.context, ) } diff --git a/packages/query-core/src/tests/hydration.test.tsx b/packages/query-core/src/tests/hydration.test.tsx index 5b6601914eb..49dd571d43c 100644 --- a/packages/query-core/src/tests/hydration.test.tsx +++ b/packages/query-core/src/tests/hydration.test.tsx @@ -364,10 +364,13 @@ describe('dehydration and rehydration', () => { retryDelay: 10, }) - executeMutation(serverClient, { - mutationKey: ['addTodo'], - variables: { text: 'text' }, - }).catch(() => undefined) + executeMutation( + serverClient, + { + mutationKey: ['addTodo'], + }, + { text: 'text' }, + ).catch(() => undefined) await sleep(50) @@ -433,10 +436,13 @@ describe('dehydration and rehydration', () => { retry: false, }) - executeMutation(queryClient, { - mutationKey: ['addTodo'], - variables: { text: 'text' }, - }).catch(() => undefined) + executeMutation( + queryClient, + { + mutationKey: ['addTodo'], + }, + { text: 'text' }, + ).catch(() => undefined) await sleep(1) const dehydrated = dehydrate(queryClient, { dehydrateMutations: false }) @@ -463,10 +469,13 @@ describe('dehydration and rehydration', () => { retryDelay: 20, }) - executeMutation(queryClient, { - mutationKey: ['addTodo'], - variables: { text: 'text' }, - }).catch(() => undefined) + executeMutation( + queryClient, + { + mutationKey: ['addTodo'], + }, + { text: 'text' }, + ).catch(() => undefined) // Dehydrate mutation between retries await sleep(1) diff --git a/packages/query-core/src/tests/mutationCache.test.tsx b/packages/query-core/src/tests/mutationCache.test.tsx index eeb7ec7c0df..f5fa0ed0bd9 100644 --- a/packages/query-core/src/tests/mutationCache.test.tsx +++ b/packages/query-core/src/tests/mutationCache.test.tsx @@ -11,12 +11,15 @@ describe('mutationCache', () => { const testClient = createQueryClient({ mutationCache: testCache }) try { - await executeMutation(testClient, { - mutationKey: key, - variables: 'vars', - mutationFn: () => Promise.reject('error'), - onMutate: () => 'context', - }) + await executeMutation( + testClient, + { + mutationKey: key, + mutationFn: () => Promise.reject('error'), + onMutate: () => 'context', + }, + 'vars', + ) } catch {} const mutation = testCache.getAll()[0] @@ -35,16 +38,19 @@ describe('mutationCache', () => { const testClient = createQueryClient({ mutationCache: testCache }) try { - await executeMutation(testClient, { - mutationKey: key, - variables: 'vars', - mutationFn: () => Promise.reject('error'), - onError: async () => { - states.push(3) - await sleep(1) - states.push(4) + await executeMutation( + testClient, + { + mutationKey: key, + mutationFn: () => Promise.reject('error'), + onError: async () => { + states.push(3) + await sleep(1) + states.push(4) + }, }, - }) + 'vars', + ) } catch {} expect(states).toEqual([1, 2, 3, 4]) @@ -58,12 +64,15 @@ describe('mutationCache', () => { const testClient = createQueryClient({ mutationCache: testCache }) try { - await executeMutation(testClient, { - mutationKey: key, - variables: 'vars', - mutationFn: () => Promise.resolve({ data: 5 }), - onMutate: () => 'context', - }) + await executeMutation( + testClient, + { + mutationKey: key, + mutationFn: () => Promise.resolve({ data: 5 }), + onMutate: () => 'context', + }, + 'vars', + ) } catch {} const mutation = testCache.getAll()[0] @@ -85,16 +94,19 @@ describe('mutationCache', () => { const testCache = new MutationCache({ onSuccess }) const testClient = createQueryClient({ mutationCache: testCache }) - await executeMutation(testClient, { - mutationKey: key, - variables: 'vars', - mutationFn: () => Promise.resolve({ data: 5 }), - onSuccess: async () => { - states.push(3) - await sleep(1) - states.push(4) + await executeMutation( + testClient, + { + mutationKey: key, + mutationFn: () => Promise.resolve({ data: 5 }), + onSuccess: async () => { + states.push(3) + await sleep(1) + states.push(4) + }, }, - }) + 'vars', + ) expect(states).toEqual([1, 2, 3, 4]) }) @@ -107,12 +119,15 @@ describe('mutationCache', () => { const testClient = createQueryClient({ mutationCache: testCache }) try { - await executeMutation(testClient, { - mutationKey: key, - variables: 'vars', - mutationFn: () => Promise.resolve({ data: 5 }), - onMutate: () => 'context', - }) + await executeMutation( + testClient, + { + mutationKey: key, + mutationFn: () => Promise.resolve({ data: 5 }), + onMutate: () => 'context', + }, + 'vars', + ) } catch {} const mutation = testCache.getAll()[0] @@ -130,16 +145,19 @@ describe('mutationCache', () => { const testCache = new MutationCache({ onMutate }) const testClient = createQueryClient({ mutationCache: testCache }) - await executeMutation(testClient, { - mutationKey: key, - variables: 'vars', - mutationFn: () => Promise.resolve({ data: 5 }), - onMutate: async () => { - states.push(3) - await sleep(1) - states.push(4) + await executeMutation( + testClient, + { + mutationKey: key, + mutationFn: () => Promise.resolve({ data: 5 }), + onMutate: async () => { + states.push(3) + await sleep(1) + states.push(4) + }, }, - }) + 'vars', + ) expect(states).toEqual([1, 2, 3, 4]) }) @@ -150,11 +168,14 @@ describe('mutationCache', () => { const testCache = new MutationCache() const testClient = createQueryClient({ mutationCache: testCache }) const key = ['mutation', 'vars'] - await executeMutation(testClient, { - mutationKey: key, - variables: 'vars', - mutationFn: () => Promise.resolve(), - }) + await executeMutation( + testClient, + { + mutationKey: key, + mutationFn: () => Promise.resolve(), + }, + 'vars', + ) const [mutation] = testCache.getAll() expect(testCache.find({ mutationKey: key })).toEqual(mutation) expect( @@ -162,7 +183,9 @@ describe('mutationCache', () => { ).toEqual(mutation) expect(testCache.find({ mutationKey: ['unknown'] })).toEqual(undefined) expect( - testCache.find({ predicate: (m) => m.options.variables === 'vars' }), + testCache.find({ + predicate: (m) => m.options.mutationKey?.[0] === key[0], + }), ).toEqual(mutation) }) }) @@ -171,30 +194,42 @@ describe('mutationCache', () => { test('should filter correctly', async () => { const testCache = new MutationCache() const testClient = createQueryClient({ mutationCache: testCache }) - await executeMutation(testClient, { - mutationKey: ['a', 1], - variables: 1, - mutationFn: () => Promise.resolve(), - }) - await executeMutation(testClient, { - mutationKey: ['a', 2], - variables: 2, - mutationFn: () => Promise.resolve(), - }) - await executeMutation(testClient, { - mutationKey: ['b'], - mutationFn: () => Promise.resolve(), - }) + await executeMutation( + testClient, + { + mutationKey: ['a', 1], + mutationFn: () => Promise.resolve(), + }, + 1, + ) + await executeMutation( + testClient, + { + mutationKey: ['a', 2], + mutationFn: () => Promise.resolve(), + }, + 2, + ) + await executeMutation( + testClient, + { + mutationKey: ['b'], + mutationFn: () => Promise.resolve(), + }, + 3, + ) const [mutation1, mutation2] = testCache.getAll() expect( testCache.findAll({ mutationKey: ['a'], exact: false }), ).toHaveLength(2) expect(testCache.find({ mutationKey: ['a', 1] })).toEqual(mutation1) - expect(testCache.findAll({ mutationKey: ['unknown'] })).toEqual([]) expect( - testCache.findAll({ predicate: (m) => m.options.variables === 2 }), + testCache.findAll({ + predicate: (m) => m.options.mutationKey?.[1] === 2, + }), ).toEqual([mutation2]) + expect(testCache.findAll({ mutationKey: ['unknown'] })).toEqual([]) }) }) @@ -203,13 +238,16 @@ describe('mutationCache', () => { const testCache = new MutationCache() const testClient = createQueryClient({ mutationCache: testCache }) const onSuccess = jest.fn() - await executeMutation(testClient, { - mutationKey: ['a', 1], - variables: 1, - cacheTime: 10, - mutationFn: () => Promise.resolve(), - onSuccess, - }) + await executeMutation( + testClient, + { + mutationKey: ['a', 1], + cacheTime: 10, + mutationFn: () => Promise.resolve(), + onSuccess, + }, + 1, + ) expect(testCache.getAll()).toHaveLength(1) await sleep(10) @@ -222,9 +260,8 @@ describe('mutationCache', () => { test('should not remove mutations if there are active observers', async () => { const queryClient = createQueryClient() const observer = new MutationObserver(queryClient, { - variables: 1, cacheTime: 10, - mutationFn: () => Promise.resolve(), + mutationFn: (input: number) => Promise.resolve(input), }) const unsubscribe = observer.subscribe(() => undefined) @@ -245,7 +282,6 @@ describe('mutationCache', () => { const queryClient = createQueryClient() const onSuccess = jest.fn() const observer = new MutationObserver(queryClient, { - variables: 1, cacheTime: 10, mutationFn: async () => { await sleep(20) @@ -272,7 +308,6 @@ describe('mutationCache', () => { const queryClient = createQueryClient() const onSuccess = jest.fn() const observer = new MutationObserver(queryClient, { - variables: 1, cacheTime: 0, mutationFn: async () => { return 'data' diff --git a/packages/query-core/src/tests/mutations.test.tsx b/packages/query-core/src/tests/mutations.test.tsx index b281259f3e7..1a765b1895d 100644 --- a/packages/query-core/src/tests/mutations.test.tsx +++ b/packages/query-core/src/tests/mutations.test.tsx @@ -15,15 +15,6 @@ describe('mutations', () => { queryClient.clear() }) - test('mutate should trigger a mutation', async () => { - const result = await executeMutation(queryClient, { - mutationFn: async (text: string) => text, - variables: 'todo', - }) - - expect(result).toBe(result) - }) - test('mutate should accept null values', async () => { let variables @@ -43,17 +34,22 @@ describe('mutations', () => { test('setMutationDefaults should be able to set defaults', async () => { const key = queryKey() + const fn = jest.fn() queryClient.setMutationDefaults(key, { - mutationFn: async (text: string) => text, + mutationFn: fn, }) - const result = await executeMutation(queryClient, { - mutationKey: key, - variables: 'todo', - }) + await executeMutation( + queryClient, + { + mutationKey: key, + }, + 'vars', + ) - expect(result).toBe(result) + expect(fn).toHaveBeenCalledTimes(1) + expect(fn).toHaveBeenCalledWith('vars') }) test('mutation should set correct success states', async () => { @@ -63,7 +59,6 @@ describe('mutations', () => { return text }, onMutate: (text) => text, - variables: 'todo', }) expect(mutation.getCurrentResult()).toEqual({ @@ -89,7 +84,7 @@ describe('mutations', () => { states.push(state) }) - mutation.mutate() + mutation.mutate('todo') await sleep(0) @@ -145,18 +140,17 @@ describe('mutations', () => { mutate: expect.any(Function), reset: expect.any(Function), status: 'success', - variables: 'todo', + variables: undefined, }) }) test('mutation should set correct error states', async () => { const mutation = new MutationObserver(queryClient, { - mutationFn: async () => { + mutationFn: async (_: string) => { await sleep(20) return Promise.reject('err') }, onMutate: (text) => text, - variables: 'todo', retry: 1, retryDelay: 1, }) @@ -167,7 +161,7 @@ describe('mutations', () => { states.push(state) }) - mutation.mutate().catch(() => undefined) + mutation.mutate('todo').catch(() => undefined) await sleep(0) @@ -242,7 +236,7 @@ describe('mutations', () => { mutate: expect.any(Function), reset: expect.any(Function), status: 'error', - variables: 'todo', + variables: undefined, }) }) @@ -300,7 +294,7 @@ describe('mutations', () => { failureReason: null, isPaused: false, status: 'success', - variables: 'todo', + variables: undefined, }) expect(onMutate).not.toHaveBeenCalled() diff --git a/packages/query-core/src/tests/utils.ts b/packages/query-core/src/tests/utils.ts index 9659fb16830..8ebc7bb80ef 100644 --- a/packages/query-core/src/tests/utils.ts +++ b/packages/query-core/src/tests/utils.ts @@ -48,17 +48,15 @@ export function setActTimeout(fn: () => void, ms?: number) { */ export const expectType = (_: T): void => undefined -/** - * Assert the parameter is not typed as `any` - */ -export const expectTypeNotAny = (_: 0 extends 1 & T ? never : T): void => - undefined - -export const executeMutation = ( +export const executeMutation = ( queryClient: QueryClient, - options: MutationOptions, -): Promise => { - return queryClient.getMutationCache().build(queryClient, options).execute() + options: MutationOptions, + variables: TVariables, +) => { + return queryClient + .getMutationCache() + .build(queryClient, options) + .execute(variables) } // This monkey-patches the isServer-value from utils, diff --git a/packages/query-core/src/types.ts b/packages/query-core/src/types.ts index f177573d49f..ec3de6c026c 100644 --- a/packages/query-core/src/types.ts +++ b/packages/query-core/src/types.ts @@ -550,7 +550,6 @@ export interface MutationOptions< > { mutationFn?: MutationFunction mutationKey?: MutationKey - variables?: TVariables onMutate?: ( variables: TVariables, ) => Promise | TContext | undefined @@ -638,6 +637,7 @@ export interface MutationObserverIdleResult< TContext = unknown, > extends MutationObserverBaseResult { data: undefined + variables: undefined error: null isError: false isIdle: true @@ -653,6 +653,7 @@ export interface MutationObserverLoadingResult< TContext = unknown, > extends MutationObserverBaseResult { data: undefined + variables: TVariables error: null isError: false isIdle: false @@ -669,6 +670,7 @@ export interface MutationObserverErrorResult< > extends MutationObserverBaseResult { data: undefined error: TError + variables: undefined isError: true isIdle: false isLoading: false @@ -684,6 +686,7 @@ export interface MutationObserverSuccessResult< > extends MutationObserverBaseResult { data: TData error: null + variables: undefined isError: false isIdle: false isLoading: false diff --git a/packages/query-persist-client-core/src/__tests__/persist.test.ts b/packages/query-persist-client-core/src/__tests__/persist.test.ts index 4c1b2a44a86..679a62f1511 100644 --- a/packages/query-persist-client-core/src/__tests__/persist.test.ts +++ b/packages/query-persist-client-core/src/__tests__/persist.test.ts @@ -33,7 +33,6 @@ describe('persistQueryClientSubscribe', () => { queryClient.getMutationCache().build(queryClient, { mutationFn: async (text: string) => text, - variables: 'todo', }) const result = await persister.restoreClient() diff --git a/packages/react-query/src/__tests__/useMutation.test.tsx b/packages/react-query/src/__tests__/useMutation.test.tsx index 9f15b2e2624..28971e4173f 100644 --- a/packages/react-query/src/__tests__/useMutation.test.tsx +++ b/packages/react-query/src/__tests__/useMutation.test.tsx @@ -982,10 +982,11 @@ describe('useMutation', () => { function Page() { const mutation = useMutation({ - mutationFn: async (_text: string) => { + mutationFn: async (text: string) => { count++ + const result = `result-${text}` await sleep(10) - return `result${count}` + return result }, onSuccess, onSettled, @@ -995,13 +996,23 @@ describe('useMutation', () => {
+
data: {mutation.data ?? 'null'}, status: {mutation.status} @@ -1014,22 +1025,38 @@ describe('useMutation', () => { await rendered.findByText('data: null, status: idle') - fireEvent.click(rendered.getByRole('button', { name: /mutate/i })) - fireEvent.click(rendered.getByRole('button', { name: /mutate/i })) + fireEvent.click(rendered.getByRole('button', { name: /mutate1/i })) + fireEvent.click(rendered.getByRole('button', { name: /mutate2/i })) - await rendered.findByText('data: result2, status: success') + await rendered.findByText('data: result-todo2, status: success') expect(count).toBe(2) expect(onSuccess).toHaveBeenCalledTimes(2) + expect(onSuccess).toHaveBeenNthCalledWith( + 1, + 'result-todo1', + 'todo1', + undefined, + ) + expect(onSuccess).toHaveBeenNthCalledWith( + 2, + 'result-todo2', + 'todo2', + undefined, + ) expect(onSettled).toHaveBeenCalledTimes(2) expect(onSuccessMutate).toHaveBeenCalledTimes(1) - expect(onSuccessMutate).toHaveBeenCalledWith('result2', 'todo', undefined) + expect(onSuccessMutate).toHaveBeenCalledWith( + 'result-todo2', + 'todo2', + undefined, + ) expect(onSettledMutate).toHaveBeenCalledTimes(1) expect(onSettledMutate).toHaveBeenCalledWith( - 'result2', + 'result-todo2', null, - 'todo', + 'todo2', undefined, ) }) From 71124d7f7edc1d2c8e6171e48eeef2af147f6c04 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Wed, 11 Jan 2023 17:32:28 +0100 Subject: [PATCH 28/60] feat: reset mutation variables in success / error case add reset tests --- .../query-core/src/tests/mutations.test.tsx | 4 +- .../src/__tests__/useMutation.test.tsx | 65 +++++++++++++++++++ 2 files changed, 66 insertions(+), 3 deletions(-) diff --git a/packages/query-core/src/tests/mutations.test.tsx b/packages/query-core/src/tests/mutations.test.tsx index 1a765b1895d..babfc6235d4 100644 --- a/packages/query-core/src/tests/mutations.test.tsx +++ b/packages/query-core/src/tests/mutations.test.tsx @@ -25,9 +25,7 @@ describe('mutations', () => { }, }) - mutation.mutate(null) - - await sleep(10) + await mutation.mutate(null) expect(variables).toBe(null) }) diff --git a/packages/react-query/src/__tests__/useMutation.test.tsx b/packages/react-query/src/__tests__/useMutation.test.tsx index 28971e4173f..55940b4fc35 100644 --- a/packages/react-query/src/__tests__/useMutation.test.tsx +++ b/packages/react-query/src/__tests__/useMutation.test.tsx @@ -1165,4 +1165,69 @@ describe('useMutation', () => { expect(onError).toHaveBeenCalledWith(mutateFnError, 'todo', undefined) }) + + it('should reset variables after successful mutation', async () => { + function Page() { + const mutation = useMutation({ + mutationFn: async (text: string) => { + await sleep(10) + return 'result-' + text + }, + }) + + return ( +
+ +
+ data: {mutation.data ?? 'null'}, status: {mutation.status}, + variables: {mutation.variables ?? 'null'} +
+
+ ) + } + + const rendered = renderWithClient(queryClient, ) + + await rendered.findByText('data: null, status: idle, variables: null') + + rendered.getByRole('button', { name: /mutate/i }).click() + + await rendered.findByText('data: null, status: loading, variables: todo') + await rendered.findByText( + 'data: result-todo, status: success, variables: null', + ) + }) + + it('should reset variables after errorneous mutation', async () => { + function Page() { + const mutation = useMutation({ + mutationFn: async (text: string) => { + await sleep(10) + throw new Error('error-' + text) + }, + }) + + return ( +
+ +
+ error:{' '} + {mutation.error instanceof Error ? mutation.error.message : 'null'}, + status: {mutation.status}, variables: {mutation.variables ?? 'null'} +
+
+ ) + } + + const rendered = renderWithClient(queryClient, ) + + await rendered.findByText('error: null, status: idle, variables: null') + + rendered.getByRole('button', { name: /mutate/i }).click() + + await rendered.findByText('error: null, status: loading, variables: todo') + await rendered.findByText( + 'error: error-todo, status: error, variables: null', + ) + }) }) From 27a73a32c26e71e6f052559ad4a459cae79394df Mon Sep 17 00:00:00 2001 From: Damian Osipiuk Date: Wed, 11 Jan 2023 23:28:34 +0000 Subject: [PATCH 29/60] test(vue-query): fix tests accessing private props --- .../src/__tests__/vueQueryPlugin.test.ts | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/packages/vue-query/src/__tests__/vueQueryPlugin.test.ts b/packages/vue-query/src/__tests__/vueQueryPlugin.test.ts index 5dfbbd9a804..9938e88e411 100644 --- a/packages/vue-query/src/__tests__/vueQueryPlugin.test.ts +++ b/packages/vue-query/src/__tests__/vueQueryPlugin.test.ts @@ -119,7 +119,7 @@ describe('VueQueryPlugin', () => { appMock._mixin.beforeCreate?.call(appMock) expect(appMock._provided).toMatchObject({ - VUE_QUERY_CLIENT: expect.objectContaining({ defaultOptions: {} }), + VUE_QUERY_CLIENT: expect.any(QueryClient), }) }) @@ -129,7 +129,7 @@ describe('VueQueryPlugin', () => { expect(appMock.provide).toHaveBeenCalledWith( VUE_QUERY_CLIENT, - expect.objectContaining({ defaultOptions: {} }), + expect.any(QueryClient), ) }) }) @@ -142,9 +142,7 @@ describe('VueQueryPlugin', () => { appMock._mixin.beforeCreate?.call(appMock) expect(appMock._provided).toMatchObject({ - [VUE_QUERY_CLIENT + ':CUSTOM']: expect.objectContaining({ - defaultOptions: {}, - }), + [VUE_QUERY_CLIENT + ':CUSTOM']: expect.any(QueryClient), }) }) @@ -154,7 +152,7 @@ describe('VueQueryPlugin', () => { expect(appMock.provide).toHaveBeenCalledWith( VUE_QUERY_CLIENT + ':CUSTOM', - expect.objectContaining({ defaultOptions: {} }), + expect.any(QueryClient), ) }) }) @@ -217,10 +215,10 @@ describe('VueQueryPlugin', () => { queryClientConfig: config, }) - expect(appMock.provide).toHaveBeenCalledWith( - VUE_QUERY_CLIENT, - expect.objectContaining(config), - ) + const client = (appMock.provide as jest.Mock).mock.calls[0][1] + const defaultOptions = client.getDefaultOptions() + + expect(defaultOptions).toEqual(config.defaultOptions) }, ) }) From a42f974409c31ddb823ca39173698b57fad70a5d Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Thu, 12 Jan 2023 12:49:18 +0100 Subject: [PATCH 30/60] feat: add useMutationVariables --- examples/react/basic-typescript/src/index.tsx | 10 +++- packages/query-core/src/mutationCache.ts | 2 +- .../src/__tests__/useIsMutating.test.tsx | 59 +++++++++++++++++-- packages/react-query/src/index.ts | 2 +- packages/react-query/src/useIsMutating.ts | 54 +++++++++++++++-- packages/vue-query/src/mutationCache.ts | 2 +- 6 files changed, 115 insertions(+), 14 deletions(-) diff --git a/examples/react/basic-typescript/src/index.tsx b/examples/react/basic-typescript/src/index.tsx index 903aa351b49..8116d24ef21 100644 --- a/examples/react/basic-typescript/src/index.tsx +++ b/examples/react/basic-typescript/src/index.tsx @@ -2,7 +2,13 @@ import * as React from "react"; import ReactDOM from "react-dom/client"; import axios from "axios"; -import { useQuery, useQueryClient, QueryClient } from "@tanstack/react-query"; +import { + useQuery, + useQueryClient, + QueryClient, + useIsMutating, + useMutationVariables, +} from "@tanstack/react-query"; import { PersistQueryClientProvider } from "@tanstack/react-query-persist-client"; import { createSyncStoragePersister } from "@tanstack/query-sync-storage-persister"; import { ReactQueryDevtools } from "@tanstack/react-query-devtools"; @@ -45,6 +51,8 @@ function Posts({ const queryClient = useQueryClient(); const { status, data, error, isFetching } = usePosts(); + const a = useIsMutating(); + return (

Posts

diff --git a/packages/query-core/src/mutationCache.ts b/packages/query-core/src/mutationCache.ts index 3f2bf11540a..ac782f9f5a1 100644 --- a/packages/query-core/src/mutationCache.ts +++ b/packages/query-core/src/mutationCache.ts @@ -137,7 +137,7 @@ export class MutationCache extends Subscribable { return this.#mutations.find((mutation) => matchMutation(filters, mutation)) } - findAll(filters: MutationFilters): Mutation[] { + findAll(filters: MutationFilters = {}): Mutation[] { return this.#mutations.filter((mutation) => matchMutation(filters, mutation), ) diff --git a/packages/react-query/src/__tests__/useIsMutating.test.tsx b/packages/react-query/src/__tests__/useIsMutating.test.tsx index 811cb45cebe..794e3df16d7 100644 --- a/packages/react-query/src/__tests__/useIsMutating.test.tsx +++ b/packages/react-query/src/__tests__/useIsMutating.test.tsx @@ -1,6 +1,6 @@ import { fireEvent, waitFor } from '@testing-library/react' import * as React from 'react' -import { useIsMutating } from '../useIsMutating' +import { useIsMutating, useMutationVariables } from '../useIsMutating' import { useMutation } from '../useMutation' import { createQueryClient, @@ -11,6 +11,7 @@ import { import { ErrorBoundary } from 'react-error-boundary' import { QueryClient } from '@tanstack/query-core' import * as MutationCacheModule from '../../../query-core/src/mutationCache' +import { screen } from 'solid-testing-library' describe('useIsMutating', () => { it('should return the number of fetching mutations', async () => { @@ -97,7 +98,7 @@ describe('useIsMutating', () => { } renderWithClient(queryClient, ) - await waitFor(() => expect(isMutatings).toEqual([0, 1, 1, 0])) + await waitFor(() => expect(isMutatings).toEqual([0, 1, 0])) }) it('should filter correctly by predicate', async () => { @@ -138,7 +139,7 @@ describe('useIsMutating', () => { } renderWithClient(queryClient, ) - await waitFor(() => expect(isMutatings).toEqual([0, 1, 1, 0])) + await waitFor(() => expect(isMutatings).toEqual([0, 1, 0])) }) it('should not change state if unmounted', async () => { @@ -238,7 +239,7 @@ describe('useIsMutating', () => { } renderWithClient(queryClient, , { context }) - await waitFor(() => expect(isMutatings).toEqual([0, 1, 1, 2, 2, 1, 0])) + await waitFor(() => expect(isMutatings).toEqual([0, 1, 2, 1, 0])) }) it('should throw if the context is not passed to useIsMutating', async () => { @@ -279,4 +280,54 @@ describe('useIsMutating', () => { await waitFor(() => rendered.getByText('error boundary')) }) }) + describe('useMutationVariables', () => { + it('should work', async () => { + const queryClient = createQueryClient() + const variables: number[][] = [] + const mutationKey = ['mutation'] + + function Variables() { + variables.push(useMutationVariables({ mutationKey })) + + return null + } + + function Mutate() { + const { mutate, data } = useMutation({ + mutationKey, + mutationFn: async (input: number) => { + await sleep(150) + return 'data' + input + }, + }) + + return ( +
+ data: {data ?? 'null'} + +
+ ) + } + + function Page() { + return ( +
+ + +
+ ) + } + + const rendered = renderWithClient(queryClient, ) + + await waitFor(() => rendered.getByText('data: null')) + + fireEvent.click(screen.getByRole('button', { name: /mutate/i })) + + await waitFor(() => rendered.getByText('data: data1')) + + expect(variables).toEqual([[], [1], []]) + console.log(variables) + }) + }) }) diff --git a/packages/react-query/src/index.ts b/packages/react-query/src/index.ts index f906c6d8471..d1acb8417e6 100644 --- a/packages/react-query/src/index.ts +++ b/packages/react-query/src/index.ts @@ -22,7 +22,7 @@ export { useQueryErrorResetBoundary, } from './QueryErrorResetBoundary' export { useIsFetching } from './useIsFetching' -export { useIsMutating } from './useIsMutating' +export { useIsMutating, useMutationVariables } from './useIsMutating' export { useMutation } from './useMutation' export { useInfiniteQuery } from './useInfiniteQuery' export { useIsRestoring, IsRestoringProvider } from './isRestoring' diff --git a/packages/react-query/src/useIsMutating.ts b/packages/react-query/src/useIsMutating.ts index 3c70eba3cfb..a48d1900cf1 100644 --- a/packages/react-query/src/useIsMutating.ts +++ b/packages/react-query/src/useIsMutating.ts @@ -1,7 +1,7 @@ import * as React from 'react' -import type { MutationFilters } from '@tanstack/query-core' -import { notifyManager } from '@tanstack/query-core' +import type { MutationFilters, Mutation } from '@tanstack/query-core' +import { notifyManager, replaceEqualDeep } from '@tanstack/query-core' import type { ContextOptions } from './types' import { useQueryClient } from './QueryClientProvider' @@ -11,16 +11,58 @@ export function useIsMutating( filters?: MutationFilters, options: Options = {}, ): number { + const queryClient = useQueryClient({ context: options.context }) + return useMutationState(() => queryClient.isMutating(filters), options) +} + +export function useMutationVariables( + filters?: MutationFilters, + options: Options = {}, +): Array { + const queryClient = useQueryClient({ context: options.context }) + return useMutationState( + () => + queryClient + .getMutationCache() + .findAll({ ...filters, fetching: true }) + .map( + (m) => + (m as any as Mutation).state.variables, + ) + .filter((v): v is TVariables => Boolean(v)), + options, + ) +} + +function useMutationState(selector: () => T, options: Options = {}): T { const queryClient = useQueryClient({ context: options.context }) const mutationCache = queryClient.getMutationCache() + const selectorRef = React.useRef(selector) + const result = React.useRef() + if (!result.current) { + result.current = selector() + } + + React.useEffect(() => { + selectorRef.current = selector + }) return React.useSyncExternalStore( React.useCallback( (onStoreChange) => - mutationCache.subscribe(notifyManager.batchCalls(onStoreChange)), + mutationCache.subscribe(() => { + const nextResult = replaceEqualDeep( + result.current, + selectorRef.current(), + ) + if (result.current !== nextResult) { + result.current = nextResult + notifyManager.schedule(onStoreChange) + } + }), [mutationCache], ), - () => queryClient.isMutating(filters), - () => queryClient.isMutating(filters), - ) + () => result.current, + () => result.current, + )! } diff --git a/packages/vue-query/src/mutationCache.ts b/packages/vue-query/src/mutationCache.ts index f0bce63b718..b0792858983 100644 --- a/packages/vue-query/src/mutationCache.ts +++ b/packages/vue-query/src/mutationCache.ts @@ -10,7 +10,7 @@ export class MutationCache extends MC { return super.find(cloneDeepUnref(filters) as MutationFilters) } - findAll(filters: MaybeRefDeep): Mutation[] { + findAll(filters: MaybeRefDeep = {}): Mutation[] { return super.findAll(cloneDeepUnref(filters) as MutationFilters) } } From 76a2bc4cabf47441f4a3ed45abbc0f240a2ed756 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Thu, 12 Jan 2023 12:51:42 +0100 Subject: [PATCH 31/60] refactor: rename useIsMutating file to useMutationState because it now exports two state related hooks --- examples/react/basic-typescript/src/index.tsx | 10 +--------- ...seIsMutating.test.tsx => useMutationState.test.tsx} | 2 +- packages/react-query/src/index.ts | 2 +- .../src/{useIsMutating.ts => useMutationState.ts} | 0 4 files changed, 3 insertions(+), 11 deletions(-) rename packages/react-query/src/__tests__/{useIsMutating.test.tsx => useMutationState.test.tsx} (99%) rename packages/react-query/src/{useIsMutating.ts => useMutationState.ts} (100%) diff --git a/examples/react/basic-typescript/src/index.tsx b/examples/react/basic-typescript/src/index.tsx index 8116d24ef21..903aa351b49 100644 --- a/examples/react/basic-typescript/src/index.tsx +++ b/examples/react/basic-typescript/src/index.tsx @@ -2,13 +2,7 @@ import * as React from "react"; import ReactDOM from "react-dom/client"; import axios from "axios"; -import { - useQuery, - useQueryClient, - QueryClient, - useIsMutating, - useMutationVariables, -} from "@tanstack/react-query"; +import { useQuery, useQueryClient, QueryClient } from "@tanstack/react-query"; import { PersistQueryClientProvider } from "@tanstack/react-query-persist-client"; import { createSyncStoragePersister } from "@tanstack/query-sync-storage-persister"; import { ReactQueryDevtools } from "@tanstack/react-query-devtools"; @@ -51,8 +45,6 @@ function Posts({ const queryClient = useQueryClient(); const { status, data, error, isFetching } = usePosts(); - const a = useIsMutating(); - return (

Posts

diff --git a/packages/react-query/src/__tests__/useIsMutating.test.tsx b/packages/react-query/src/__tests__/useMutationState.test.tsx similarity index 99% rename from packages/react-query/src/__tests__/useIsMutating.test.tsx rename to packages/react-query/src/__tests__/useMutationState.test.tsx index 794e3df16d7..bce99479d1c 100644 --- a/packages/react-query/src/__tests__/useIsMutating.test.tsx +++ b/packages/react-query/src/__tests__/useMutationState.test.tsx @@ -1,6 +1,6 @@ import { fireEvent, waitFor } from '@testing-library/react' import * as React from 'react' -import { useIsMutating, useMutationVariables } from '../useIsMutating' +import { useIsMutating, useMutationVariables } from '../useMutationState' import { useMutation } from '../useMutation' import { createQueryClient, diff --git a/packages/react-query/src/index.ts b/packages/react-query/src/index.ts index d1acb8417e6..c07a0fbc428 100644 --- a/packages/react-query/src/index.ts +++ b/packages/react-query/src/index.ts @@ -22,7 +22,7 @@ export { useQueryErrorResetBoundary, } from './QueryErrorResetBoundary' export { useIsFetching } from './useIsFetching' -export { useIsMutating, useMutationVariables } from './useIsMutating' +export { useIsMutating, useMutationVariables } from './useMutationState' export { useMutation } from './useMutation' export { useInfiniteQuery } from './useInfiniteQuery' export { useIsRestoring, IsRestoringProvider } from './isRestoring' diff --git a/packages/react-query/src/useIsMutating.ts b/packages/react-query/src/useMutationState.ts similarity index 100% rename from packages/react-query/src/useIsMutating.ts rename to packages/react-query/src/useMutationState.ts From bb017c1f3b49c645b0701a3818eae8de951be1e9 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Thu, 12 Jan 2023 12:52:34 +0100 Subject: [PATCH 32/60] refactor: restructure tests --- .../src/__tests__/useMutationState.test.tsx | 79 ++++++++++--------- 1 file changed, 40 insertions(+), 39 deletions(-) diff --git a/packages/react-query/src/__tests__/useMutationState.test.tsx b/packages/react-query/src/__tests__/useMutationState.test.tsx index bce99479d1c..1990d96950e 100644 --- a/packages/react-query/src/__tests__/useMutationState.test.tsx +++ b/packages/react-query/src/__tests__/useMutationState.test.tsx @@ -280,54 +280,55 @@ describe('useIsMutating', () => { await waitFor(() => rendered.getByText('error boundary')) }) }) - describe('useMutationVariables', () => { - it('should work', async () => { - const queryClient = createQueryClient() - const variables: number[][] = [] - const mutationKey = ['mutation'] +}) - function Variables() { - variables.push(useMutationVariables({ mutationKey })) +describe('useMutationVariables', () => { + it('should return variables after calling mutate', async () => { + const queryClient = createQueryClient() + const variables: number[][] = [] + const mutationKey = ['mutation'] - return null - } + function Variables() { + variables.push(useMutationVariables({ mutationKey })) - function Mutate() { - const { mutate, data } = useMutation({ - mutationKey, - mutationFn: async (input: number) => { - await sleep(150) - return 'data' + input - }, - }) + return null + } - return ( -
- data: {data ?? 'null'} - -
- ) - } + function Mutate() { + const { mutate, data } = useMutation({ + mutationKey, + mutationFn: async (input: number) => { + await sleep(150) + return 'data' + input + }, + }) - function Page() { - return ( -
- - -
- ) - } + return ( +
+ data: {data ?? 'null'} + +
+ ) + } + + function Page() { + return ( +
+ + +
+ ) + } - const rendered = renderWithClient(queryClient, ) + const rendered = renderWithClient(queryClient, ) - await waitFor(() => rendered.getByText('data: null')) + await waitFor(() => rendered.getByText('data: null')) - fireEvent.click(screen.getByRole('button', { name: /mutate/i })) + fireEvent.click(screen.getByRole('button', { name: /mutate/i })) - await waitFor(() => rendered.getByText('data: data1')) + await waitFor(() => rendered.getByText('data: data1')) - expect(variables).toEqual([[], [1], []]) - console.log(variables) - }) + expect(variables).toEqual([[], [1], []]) + console.log(variables) }) }) From eb369b154e5df06c441b47047c927c56bbe53c4c Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Thu, 12 Jan 2023 16:51:50 +0100 Subject: [PATCH 33/60] refactor: move getMutationVariables to the query-core so that other adapters can use it as well --- packages/query-core/src/queryClient.ts | 8 ++++++++ packages/react-query/src/useMutationState.ts | 12 ++---------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/packages/query-core/src/queryClient.ts b/packages/query-core/src/queryClient.ts index 7673ee1f565..38be6b2e4ae 100644 --- a/packages/query-core/src/queryClient.ts +++ b/packages/query-core/src/queryClient.ts @@ -116,6 +116,14 @@ export class QueryClient { return this.#mutationCache.findAll({ ...filters, fetching: true }).length } + getMutationVariables( + filters?: MutationFilters, + ): TVariables[] { + return this.#mutationCache + .findAll(filters) + .map((mutation) => mutation.state.variables) + .filter(Boolean) as unknown as TVariables[] + } getQueryData( queryKey: QueryKey, ): TQueryFnData | undefined { diff --git a/packages/react-query/src/useMutationState.ts b/packages/react-query/src/useMutationState.ts index a48d1900cf1..ad9ba952c23 100644 --- a/packages/react-query/src/useMutationState.ts +++ b/packages/react-query/src/useMutationState.ts @@ -1,6 +1,6 @@ import * as React from 'react' -import type { MutationFilters, Mutation } from '@tanstack/query-core' +import type { MutationFilters } from '@tanstack/query-core' import { notifyManager, replaceEqualDeep } from '@tanstack/query-core' import type { ContextOptions } from './types' import { useQueryClient } from './QueryClientProvider' @@ -21,15 +21,7 @@ export function useMutationVariables( ): Array { const queryClient = useQueryClient({ context: options.context }) return useMutationState( - () => - queryClient - .getMutationCache() - .findAll({ ...filters, fetching: true }) - .map( - (m) => - (m as any as Mutation).state.variables, - ) - .filter((v): v is TVariables => Boolean(v)), + () => queryClient.getMutationVariables(filters), options, ) } From b0e62c75d7f3d3a5778a7c1749201357c3ede31e Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Thu, 12 Jan 2023 16:56:57 +0100 Subject: [PATCH 34/60] docs: rewrite optimistic updates example --- .../next-env.d.ts | 5 ++- .../pages/index.tsx | 43 ++++--------------- .../tsconfig.json | 3 +- 3 files changed, 14 insertions(+), 37 deletions(-) diff --git a/examples/react/optimistic-updates-typescript/next-env.d.ts b/examples/react/optimistic-updates-typescript/next-env.d.ts index 7b7aa2c7727..4f11a03dc6c 100644 --- a/examples/react/optimistic-updates-typescript/next-env.d.ts +++ b/examples/react/optimistic-updates-typescript/next-env.d.ts @@ -1,2 +1,5 @@ /// -/// +/// + +// NOTE: This file should not be edited +// see https://nextjs.org/docs/basic-features/typescript for more information. diff --git a/examples/react/optimistic-updates-typescript/pages/index.tsx b/examples/react/optimistic-updates-typescript/pages/index.tsx index 7837021e180..93172e397a2 100755 --- a/examples/react/optimistic-updates-typescript/pages/index.tsx +++ b/examples/react/optimistic-updates-typescript/pages/index.tsx @@ -35,41 +35,8 @@ function Example() { const { isFetching, ...queryInfo } = useTodos() const addTodoMutation = useMutation({ - mutationFn: (newTodo) => axios.post('/api/data', { text: newTodo }), - // When mutate is called: - onMutate: async (newTodo: string) => { - setText('') - // Cancel any outgoing refetches - // (so they don't overwrite our optimistic update) - await queryClient.cancelQueries({ queryKey: ['todos'] }) - - // Snapshot the previous value - const previousTodos = queryClient.getQueryData(['todos']) - - // Optimistically update to the new value - if (previousTodos) { - queryClient.setQueryData(['todos'], { - ...previousTodos, - items: [ - ...previousTodos.items, - { id: Math.random().toString(), text: newTodo }, - ], - }) - } - - return { previousTodos } - }, - // If the mutation fails, - // use the context returned from onMutate to roll back - onError: (err, variables, context) => { - if (context?.previousTodos) { - queryClient.setQueryData(['todos'], context.previousTodos) - } - }, - // Always refetch after error or success: - onSettled: () => { - queryClient.invalidateQueries({ queryKey: ['todos'] }) - }, + mutationFn: (newTodo: string) => axios.post('/api/data', { text: newTodo }), + onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), }) return ( @@ -85,6 +52,7 @@ function Example() {
{ e.preventDefault() + setText('') addTodoMutation.mutate(text) }} > @@ -106,6 +74,11 @@ function Example() { {queryInfo.data.items.map((todo) => (
  • {todo.text}
  • ))} + {addTodoMutation.variables && ( +
  • + {addTodoMutation.variables} +
  • + )} {isFetching &&
    Updating in background...
    } diff --git a/examples/react/optimistic-updates-typescript/tsconfig.json b/examples/react/optimistic-updates-typescript/tsconfig.json index 1087618126c..7f1edf84a63 100644 --- a/examples/react/optimistic-updates-typescript/tsconfig.json +++ b/examples/react/optimistic-updates-typescript/tsconfig.json @@ -18,7 +18,8 @@ "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, - "isolatedModules": true + "isolatedModules": true, + "incremental": true }, "exclude": [ "node_modules" From 42c4a57701ae08042307c37545a853f278a32947 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Thu, 12 Jan 2023 20:33:47 +0100 Subject: [PATCH 35/60] refactor: don't reset variables we can keep them in store so that they are always accessible, and have the user check for `isLoading` instead --- .../pages/index.tsx | 2 +- packages/query-core/src/mutation.ts | 17 +++++------------ packages/query-core/src/mutationObserver.ts | 8 ++++---- .../src/__tests__/useMutationState.test.tsx | 4 +++- 4 files changed, 13 insertions(+), 18 deletions(-) diff --git a/examples/react/optimistic-updates-typescript/pages/index.tsx b/examples/react/optimistic-updates-typescript/pages/index.tsx index 93172e397a2..1197839ee25 100755 --- a/examples/react/optimistic-updates-typescript/pages/index.tsx +++ b/examples/react/optimistic-updates-typescript/pages/index.tsx @@ -74,7 +74,7 @@ function Example() { {queryInfo.data.items.map((todo) => (
  • {todo.text}
  • ))} - {addTodoMutation.variables && ( + {addTodoMutation.isLoading && (
  • {addTodoMutation.variables}
  • diff --git a/packages/query-core/src/mutation.ts b/packages/query-core/src/mutation.ts index 194f6931006..c86c819f3ba 100644 --- a/packages/query-core/src/mutation.ts +++ b/packages/query-core/src/mutation.ts @@ -48,16 +48,14 @@ interface LoadingAction { context?: TContext } -interface SuccessAction { +interface SuccessAction { type: 'success' data: TData - variables: TVariables } -interface ErrorAction { +interface ErrorAction { type: 'error' error: TError - variables: TVariables } interface PauseAction { @@ -70,11 +68,11 @@ interface ContinueAction { export type Action = | ContinueAction - | ErrorAction + | ErrorAction | FailedAction | LoadingAction | PauseAction - | SuccessAction + | SuccessAction // CLASS @@ -207,8 +205,6 @@ export class Mutation< } // this makes sure variables are set even if the mutation is restored // in which case we call execute without input - // we need to store variables here because dispatching success or error - // will reset the variables to undefined and then onSuccess and other callbacks won't see them variables = this.state.variables const data = await executeMutation() @@ -224,7 +220,7 @@ export class Mutation< await this.options.onSettled?.(data, null, variables!, this.state.context) - this.#dispatch({ type: 'success', data, variables: variables! }) + this.#dispatch({ type: 'success', data }) return data } catch (error) { try { @@ -257,7 +253,6 @@ export class Mutation< this.#dispatch({ type: 'error', error: error as TError, - variables: variables!, }) } } @@ -305,7 +300,6 @@ export class Mutation< error: null, status: 'success', isPaused: false, - variables: undefined, } case 'error': return { @@ -316,7 +310,6 @@ export class Mutation< failureReason: action.error, isPaused: false, status: 'error', - variables: undefined, } } } diff --git a/packages/query-core/src/mutationObserver.ts b/packages/query-core/src/mutationObserver.ts index b96c06a22a4..6d8989d63d2 100644 --- a/packages/query-core/src/mutationObserver.ts +++ b/packages/query-core/src/mutationObserver.ts @@ -136,25 +136,25 @@ export class MutationObserver< if (action?.type === 'success') { this.#mutateOptions.onSuccess?.( action.data, - action.variables, + this.#currentResult.variables!, this.#currentResult.context!, ) this.#mutateOptions.onSettled?.( action.data, null, - action.variables, + this.#currentResult.variables!, this.#currentResult.context, ) } else if (action?.type === 'error') { this.#mutateOptions.onError?.( action.error, - action.variables, + this.#currentResult.variables!, this.#currentResult.context, ) this.#mutateOptions.onSettled?.( undefined, action.error, - action.variables, + this.#currentResult.variables!, this.#currentResult.context, ) } diff --git a/packages/react-query/src/__tests__/useMutationState.test.tsx b/packages/react-query/src/__tests__/useMutationState.test.tsx index 1990d96950e..85ad512709f 100644 --- a/packages/react-query/src/__tests__/useMutationState.test.tsx +++ b/packages/react-query/src/__tests__/useMutationState.test.tsx @@ -289,7 +289,9 @@ describe('useMutationVariables', () => { const mutationKey = ['mutation'] function Variables() { - variables.push(useMutationVariables({ mutationKey })) + variables.push( + useMutationVariables({ mutationKey, fetching: true }), + ) return null } From 0c8ef531a9d723af70c64acae72225cf1fb1f605 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Thu, 12 Jan 2023 22:10:59 +0100 Subject: [PATCH 36/60] fix: revert tests back we have variables again --- packages/query-core/src/tests/mutations.test.tsx | 6 +++--- packages/react-query/src/__tests__/useMutation.test.tsx | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/query-core/src/tests/mutations.test.tsx b/packages/query-core/src/tests/mutations.test.tsx index babfc6235d4..50e630f1f7e 100644 --- a/packages/query-core/src/tests/mutations.test.tsx +++ b/packages/query-core/src/tests/mutations.test.tsx @@ -138,7 +138,7 @@ describe('mutations', () => { mutate: expect.any(Function), reset: expect.any(Function), status: 'success', - variables: undefined, + variables: 'todo', }) }) @@ -234,7 +234,7 @@ describe('mutations', () => { mutate: expect.any(Function), reset: expect.any(Function), status: 'error', - variables: undefined, + variables: 'todo', }) }) @@ -292,7 +292,7 @@ describe('mutations', () => { failureReason: null, isPaused: false, status: 'success', - variables: undefined, + variables: 'todo', }) expect(onMutate).not.toHaveBeenCalled() diff --git a/packages/react-query/src/__tests__/useMutation.test.tsx b/packages/react-query/src/__tests__/useMutation.test.tsx index 55940b4fc35..4c0e95d595f 100644 --- a/packages/react-query/src/__tests__/useMutation.test.tsx +++ b/packages/react-query/src/__tests__/useMutation.test.tsx @@ -1194,7 +1194,7 @@ describe('useMutation', () => { await rendered.findByText('data: null, status: loading, variables: todo') await rendered.findByText( - 'data: result-todo, status: success, variables: null', + 'data: result-todo, status: success, variables: todo', ) }) @@ -1227,7 +1227,7 @@ describe('useMutation', () => { await rendered.findByText('error: null, status: loading, variables: todo') await rendered.findByText( - 'error: error-todo, status: error, variables: null', + 'error: error-todo, status: error, variables: todo', ) }) }) From 71986d04e43daf9f7aec98e4f64e0af0ea28769b Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Thu, 12 Jan 2023 22:12:04 +0100 Subject: [PATCH 37/60] refactor: use optional chaining --- packages/query-core/src/mutationObserver.ts | 4 +--- packages/query-core/src/query.ts | 8 ++------ 2 files changed, 3 insertions(+), 9 deletions(-) diff --git a/packages/query-core/src/mutationObserver.ts b/packages/query-core/src/mutationObserver.ts index 6d8989d63d2..1d17f436ee8 100644 --- a/packages/query-core/src/mutationObserver.ts +++ b/packages/query-core/src/mutationObserver.ts @@ -98,9 +98,7 @@ export class MutationObserver< ): Promise { this.#mutateOptions = options - if (this.#currentMutation) { - this.#currentMutation.removeObserver(this) - } + this.#currentMutation?.removeObserver(this) this.#currentMutation = this.#client .getMutationCache() diff --git a/packages/query-core/src/query.ts b/packages/query-core/src/query.ts index e8ad9eb5ad4..1c0261d2a41 100644 --- a/packages/query-core/src/query.ts +++ b/packages/query-core/src/query.ts @@ -262,9 +262,7 @@ export class Query< onFocus(): void { const observer = this.#observers.find((x) => x.shouldFetchOnWindowFocus()) - if (observer) { - observer.refetch({ cancelRefetch: false }) - } + observer?.refetch({ cancelRefetch: false }) // Continue fetch if currently paused this.#retryer?.continue() @@ -273,9 +271,7 @@ export class Query< onOnline(): void { const observer = this.#observers.find((x) => x.shouldFetchOnReconnect()) - if (observer) { - observer.refetch({ cancelRefetch: false }) - } + observer?.refetch({ cancelRefetch: false }) // Continue fetch if currently paused this.#retryer?.continue() From 6dca646032113bd0ec00ca25ade59ed6b2e13e12 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Fri, 13 Jan 2023 12:51:53 +0100 Subject: [PATCH 38/60] remove unnecessary condition --- .../src/__tests__/useInfiniteQuery.test.tsx | 38 +++++++++---------- 1 file changed, 17 insertions(+), 21 deletions(-) diff --git a/packages/react-query/src/__tests__/useInfiniteQuery.test.tsx b/packages/react-query/src/__tests__/useInfiniteQuery.test.tsx index 821bc0729fa..571bd95d37c 100644 --- a/packages/react-query/src/__tests__/useInfiniteQuery.test.tsx +++ b/packages/react-query/src/__tests__/useInfiniteQuery.test.tsx @@ -849,14 +849,12 @@ describe('useInfiniteQuery', () => { Promise, [QueryFunctionContext] >(async ({ pageParam = start, signal }) => { - if (signal) { - const onAbort = jest.fn() - const abortListener = jest.fn() - onAborts.push(onAbort) - abortListeners.push(abortListener) - signal.onabort = onAbort - signal.addEventListener('abort', abortListener) - } + const onAbort = jest.fn() + const abortListener = jest.fn() + onAborts.push(onAbort) + abortListeners.push(abortListener) + signal.onabort = onAbort + signal.addEventListener('abort', abortListener) await sleep(50) return Number(pageParam) }) @@ -894,7 +892,7 @@ describe('useInfiniteQuery', () => { expect(firstCtx.pageParam).toBeUndefined() expect(firstCtx.queryKey).toEqual(key) expect(firstCtx.signal).toBeInstanceOf(AbortSignal) - expect(firstCtx.signal?.aborted).toBe(false) + expect(firstCtx.signal.aborted).toBe(false) expect(onAborts[callIndex]).not.toHaveBeenCalled() expect(abortListeners[callIndex]).not.toHaveBeenCalled() @@ -903,7 +901,7 @@ describe('useInfiniteQuery', () => { expect(secondCtx.pageParam).toBe(11) expect(secondCtx.queryKey).toEqual(key) expect(secondCtx.signal).toBeInstanceOf(AbortSignal) - expect(secondCtx.signal?.aborted).toBe(true) + expect(secondCtx.signal.aborted).toBe(true) expect(onAborts[callIndex]).toHaveBeenCalledTimes(1) expect(abortListeners[callIndex]).toHaveBeenCalledTimes(1) @@ -912,7 +910,7 @@ describe('useInfiniteQuery', () => { expect(thirdCtx.pageParam).toBe(11) expect(thirdCtx.queryKey).toEqual(key) expect(thirdCtx.signal).toBeInstanceOf(AbortSignal) - expect(thirdCtx.signal?.aborted).toBe(false) + expect(thirdCtx.signal.aborted).toBe(false) expect(onAborts[callIndex]).not.toHaveBeenCalled() expect(abortListeners[callIndex]).not.toHaveBeenCalled() }) @@ -926,14 +924,12 @@ describe('useInfiniteQuery', () => { Promise, [QueryFunctionContext] >(async ({ pageParam = start, signal }) => { - if (signal) { - const onAbort = jest.fn() - const abortListener = jest.fn() - onAborts.push(onAbort) - abortListeners.push(abortListener) - signal.onabort = onAbort - signal.addEventListener('abort', abortListener) - } + const onAbort = jest.fn() + const abortListener = jest.fn() + onAborts.push(onAbort) + abortListeners.push(abortListener) + signal.onabort = onAbort + signal.addEventListener('abort', abortListener) await sleep(50) return Number(pageParam) }) @@ -971,7 +967,7 @@ describe('useInfiniteQuery', () => { expect(firstCtx.pageParam).toBeUndefined() expect(firstCtx.queryKey).toEqual(key) expect(firstCtx.signal).toBeInstanceOf(AbortSignal) - expect(firstCtx.signal?.aborted).toBe(false) + expect(firstCtx.signal.aborted).toBe(false) expect(onAborts[callIndex]).not.toHaveBeenCalled() expect(abortListeners[callIndex]).not.toHaveBeenCalled() @@ -980,7 +976,7 @@ describe('useInfiniteQuery', () => { expect(secondCtx.pageParam).toBe(11) expect(secondCtx.queryKey).toEqual(key) expect(secondCtx.signal).toBeInstanceOf(AbortSignal) - expect(secondCtx.signal?.aborted).toBe(false) + expect(secondCtx.signal.aborted).toBe(false) expect(onAborts[callIndex]).not.toHaveBeenCalled() expect(abortListeners[callIndex]).not.toHaveBeenCalled() }) From 6c70e64959045cb1afdec7eba3e00a2a8ee3974d Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Fri, 13 Jan 2023 13:05:28 +0100 Subject: [PATCH 39/60] refactor: remove defaultOptions from mutation.ts the options we pass in are already defaulted, and we don't do anything else with them --- packages/query-core/src/mutation.ts | 11 +++-------- packages/query-core/src/mutationCache.ts | 3 --- 2 files changed, 3 insertions(+), 11 deletions(-) diff --git a/packages/query-core/src/mutation.ts b/packages/query-core/src/mutation.ts index c86c819f3ba..8ce2fcb015a 100644 --- a/packages/query-core/src/mutation.ts +++ b/packages/query-core/src/mutation.ts @@ -15,9 +15,7 @@ interface MutationConfig { mutationCache: MutationCache options: MutationOptions logger?: Logger - defaultOptions?: MutationOptions state?: MutationState - meta?: MutationMeta } export interface MutationState< @@ -83,8 +81,8 @@ export class Mutation< TContext = unknown, > extends Removable { state: MutationState - options: MutationOptions - mutationId: number + readonly options: MutationOptions + readonly mutationId: number #observers: MutationObserver[] #mutationCache: MutationCache @@ -94,10 +92,7 @@ export class Mutation< constructor(config: MutationConfig) { super() - this.options = { - ...config.defaultOptions, - ...config.options, - } + this.options = config.options this.mutationId = config.mutationId this.#mutationCache = config.mutationCache this.#logger = config.logger || defaultLogger diff --git a/packages/query-core/src/mutationCache.ts b/packages/query-core/src/mutationCache.ts index ac782f9f5a1..33cff02fdae 100644 --- a/packages/query-core/src/mutationCache.ts +++ b/packages/query-core/src/mutationCache.ts @@ -95,9 +95,6 @@ export class MutationCache extends Subscribable { mutationId: ++this.#mutationId, options: client.defaultMutationOptions(options), state, - defaultOptions: options.mutationKey - ? client.getMutationDefaults(options.mutationKey) - : undefined, }) this.add(mutation) From 01d0073043a019102c7c7f56ac320bfcb99a177d Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Fri, 13 Jan 2023 20:54:11 +0100 Subject: [PATCH 40/60] resolve merge conflict --- packages/query-core/src/index.ts | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/packages/query-core/src/index.ts b/packages/query-core/src/index.ts index 8a95a6cddf2..ede848cdd1e 100644 --- a/packages/query-core/src/index.ts +++ b/packages/query-core/src/index.ts @@ -11,13 +11,7 @@ export { MutationObserver } from './mutationObserver' export { notifyManager } from './notifyManager' export { focusManager } from './focusManager' export { onlineManager } from './onlineManager' -export { - hashKey, - replaceEqualDeep, - isError, - isServer, - keepPreviousData, -} from './utils' +export { hashKey, replaceEqualDeep, isServer, keepPreviousData } from './utils' export type { MutationFilters, QueryFilters, Updater } from './utils' export { isCancelledError } from './retryer' export { dehydrate, hydrate } from './hydration' From abdce2ec327454566fdb2ee3b4731c01eeaf4ea3 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Fri, 13 Jan 2023 22:36:38 +0100 Subject: [PATCH 41/60] refactor: make input to executeMutation required --- packages/query-core/src/mutation.ts | 21 ++++++++----------- packages/query-core/src/mutationObserver.ts | 2 +- .../src/tests/mutationObserver.test.tsx | 2 +- packages/react-query/src/__tests__/utils.tsx | 9 +------- 4 files changed, 12 insertions(+), 22 deletions(-) diff --git a/packages/query-core/src/mutation.ts b/packages/query-core/src/mutation.ts index c8a06946bd8..7ef4c98ecc6 100644 --- a/packages/query-core/src/mutation.ts +++ b/packages/query-core/src/mutation.ts @@ -149,17 +149,18 @@ export class Mutation< this.#retryer.continue() return this.#retryer.promise } - return this.execute() + // continuing a mutation assumes that variables are set, mutation must have been dehydrated before + return this.execute(this.state.variables!) } - async execute(input?: TVariables): Promise { + async execute(variables: TVariables): Promise { const executeMutation = () => { this.#retryer = createRetryer({ fn: () => { if (!this.options.mutationFn) { return Promise.reject('No mutationFn found') } - return this.options.mutationFn(this.state.variables!) + return this.options.mutationFn(variables) }, onFail: (failureCount, error) => { this.#dispatch({ type: 'failed', failureCount, error }) @@ -179,7 +180,6 @@ export class Mutation< } const restored = this.state.status === 'loading' - let variables: TVariables | undefined = input try { if (!restored) { @@ -189,7 +189,7 @@ export class Mutation< variables, this as Mutation, ) - const context = await this.options.onMutate?.(variables!) + const context = await this.options.onMutate?.(variables) if (context !== this.state.context) { this.#dispatch({ type: 'loading', @@ -198,9 +198,6 @@ export class Mutation< }) } } - // this makes sure variables are set even if the mutation is restored - // in which case we call execute without input - variables = this.state.variables const data = await executeMutation() // Notify cache callback @@ -211,9 +208,9 @@ export class Mutation< this as Mutation, ) - await this.options.onSuccess?.(data, variables!, this.state.context!) + await this.options.onSuccess?.(data, variables, this.state.context!) - await this.options.onSettled?.(data, null, variables!, this.state.context) + await this.options.onSettled?.(data, null, variables, this.state.context) this.#dispatch({ type: 'success', data }) return data @@ -233,14 +230,14 @@ export class Mutation< await this.options.onError?.( error as TError, - variables!, + variables, this.state.context, ) await this.options.onSettled?.( undefined, error as TError, - variables!, + variables, this.state.context, ) throw error diff --git a/packages/query-core/src/mutationObserver.ts b/packages/query-core/src/mutationObserver.ts index 1d17f436ee8..5bca02acbcd 100644 --- a/packages/query-core/src/mutationObserver.ts +++ b/packages/query-core/src/mutationObserver.ts @@ -93,7 +93,7 @@ export class MutationObserver< } mutate( - variables?: TVariables, + variables: TVariables, options?: MutateOptions, ): Promise { this.#mutateOptions = options diff --git a/packages/query-core/src/tests/mutationObserver.test.tsx b/packages/query-core/src/tests/mutationObserver.test.tsx index 1ca53454005..7af9534222a 100644 --- a/packages/query-core/src/tests/mutationObserver.test.tsx +++ b/packages/query-core/src/tests/mutationObserver.test.tsx @@ -29,7 +29,7 @@ describe('mutationObserver', () => { const unsubscribe1 = mutation.subscribe(subscription1Handler) const unsubscribe2 = mutation.subscribe(subscription2Handler) - mutation.mutate() + mutation.mutate('input') unsubscribe1() diff --git a/packages/react-query/src/__tests__/utils.tsx b/packages/react-query/src/__tests__/utils.tsx index d5502a3e299..048583e0b92 100644 --- a/packages/react-query/src/__tests__/utils.tsx +++ b/packages/react-query/src/__tests__/utils.tsx @@ -1,6 +1,6 @@ import * as React from 'react' import { act, render } from '@testing-library/react' -import type { ContextOptions, QueryClientConfig, MutationOptions } from '..' +import type { ContextOptions, QueryClientConfig } from '..' import { QueryClient, QueryClientProvider } from '..' import * as utils from '@tanstack/query-core' @@ -98,13 +98,6 @@ export function expectTypeNotAny(_: 0 extends 1 & T ? never : T): void { return undefined } -export function executeMutation( - queryClient: QueryClient, - options: MutationOptions, -): Promise { - return queryClient.getMutationCache().build(queryClient, options).execute() -} - // This monkey-patches the isServer-value from utils, // so that we can pretend to be in a server environment export function setIsServer(isServer: boolean) { From f2b8dcd217ed0006ec536b46e7b8118c1070bf47 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Fri, 13 Jan 2023 23:21:47 +0100 Subject: [PATCH 42/60] stabilize test default interval check for waitFor is 50ms --- packages/react-query/src/__tests__/suspense.test.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/react-query/src/__tests__/suspense.test.tsx b/packages/react-query/src/__tests__/suspense.test.tsx index 30d75fcfc28..b29ee5eebb7 100644 --- a/packages/react-query/src/__tests__/suspense.test.tsx +++ b/packages/react-query/src/__tests__/suspense.test.tsx @@ -1066,10 +1066,10 @@ describe('useQueries with suspense', () => { queryKey: key2, queryFn: async () => { results.push('2') - await sleep(20) + await sleep(50) return '2' }, - staleTime: 1000, + staleTime: 2000, suspense: false, }, ], From b6201924fcf09c3eac59cf3b477569b3d92de6fe Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Sun, 15 Jan 2023 15:16:50 +0100 Subject: [PATCH 43/60] fix: don't filter out nullish variables we can include them because we filter for "running" mutations anyways, and we don't kjnow which type the variables might have. --- packages/query-core/src/queryClient.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/query-core/src/queryClient.ts b/packages/query-core/src/queryClient.ts index 38be6b2e4ae..f45ffa4d434 100644 --- a/packages/query-core/src/queryClient.ts +++ b/packages/query-core/src/queryClient.ts @@ -121,8 +121,7 @@ export class QueryClient { ): TVariables[] { return this.#mutationCache .findAll(filters) - .map((mutation) => mutation.state.variables) - .filter(Boolean) as unknown as TVariables[] + .map((mutation) => mutation.state.variables as unknown as TVariables) } getQueryData( queryKey: QueryKey, From 2bc57ebb56b85a95d85e46d7e49bd6f22cbcf307 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Fri, 20 Jan 2023 22:27:41 +0100 Subject: [PATCH 44/60] remove unused export --- packages/react-query/src/__tests__/utils.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/react-query/src/__tests__/utils.tsx b/packages/react-query/src/__tests__/utils.tsx index b7af41d5d4b..4a992a7cd0c 100644 --- a/packages/react-query/src/__tests__/utils.tsx +++ b/packages/react-query/src/__tests__/utils.tsx @@ -1,6 +1,6 @@ import * as React from 'react' import { act, render } from '@testing-library/react' -import type { QueryClientConfig, MutationOptions } from '..' +import type { QueryClientConfig } from '..' import { QueryClient, QueryClientProvider } from '..' import * as utils from '@tanstack/query-core' From a5c7db3f4b919e6fbb0077941556c7876d5ac814 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Fri, 20 Jan 2023 22:43:41 +0100 Subject: [PATCH 45/60] fix merge conflict custom clients need to be forwarded --- packages/react-query/src/useMutationState.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/react-query/src/useMutationState.ts b/packages/react-query/src/useMutationState.ts index 55b347625e0..c63596f571c 100644 --- a/packages/react-query/src/useMutationState.ts +++ b/packages/react-query/src/useMutationState.ts @@ -9,7 +9,7 @@ export function useIsMutating( queryClient?: QueryClient, ): number { const client = useQueryClient(queryClient) - return useMutationState(() => client.isMutating(filters)) + return useMutationState(() => client.isMutating(filters), client) } export function useMutationVariables( @@ -17,7 +17,7 @@ export function useMutationVariables( queryClient?: QueryClient, ): Array { const client = useQueryClient(queryClient) - return useMutationState(() => client.getMutationVariables(filters)) + return useMutationState(() => client.getMutationVariables(filters), client) } function useMutationState(selector: () => T, queryClient?: QueryClient): T { From 367a3c60d6d76979030ffe54eba50c4a676ea7bd Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Fri, 20 Jan 2023 23:14:28 +0100 Subject: [PATCH 46/60] remove leftover console log --- packages/react-query/src/__tests__/useMutationState.test.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/react-query/src/__tests__/useMutationState.test.tsx b/packages/react-query/src/__tests__/useMutationState.test.tsx index a06994e758a..bba0a81595e 100644 --- a/packages/react-query/src/__tests__/useMutationState.test.tsx +++ b/packages/react-query/src/__tests__/useMutationState.test.tsx @@ -277,6 +277,5 @@ describe('useMutationVariables', () => { await waitFor(() => rendered.getByText('data: data1')) expect(variables).toEqual([[], [1], []]) - console.log(variables) }) }) From 4e7c7092af86541b7a743c18869419a07cda58f0 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Mon, 30 Jan 2023 16:20:17 +0100 Subject: [PATCH 47/60] feat: expose submittedAt timestamp from useMutation --- docs/react/reference/useMutation.md | 4 ++++ examples/react/optimistic-updates-typescript/pages/index.tsx | 5 ++++- packages/query-core/src/mutation.ts | 3 +++ 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/docs/react/reference/useMutation.md b/docs/react/reference/useMutation.md index f520e50ff4f..5cb0f0cdabf 100644 --- a/docs/react/reference/useMutation.md +++ b/docs/react/reference/useMutation.md @@ -18,6 +18,7 @@ const { mutateAsync, reset, status, + submittedAt } = useMutation({ mutationFn, gcTime, @@ -139,4 +140,7 @@ mutate(variables, { - `failureReason: null | TError` - The failure reason for the mutation retry. - Reset to `null` when the mutation succeeds. +- `submittedAt: number` + - The timestamp for when the mutation was submitted. + - Defaults to `0`. diff --git a/examples/react/optimistic-updates-typescript/pages/index.tsx b/examples/react/optimistic-updates-typescript/pages/index.tsx index 1197839ee25..f236f7256e2 100755 --- a/examples/react/optimistic-updates-typescript/pages/index.tsx +++ b/examples/react/optimistic-updates-typescript/pages/index.tsx @@ -75,7 +75,10 @@ function Example() {
  • {todo.text}
  • ))} {addTodoMutation.isLoading && ( -
  • +
  • {addTodoMutation.variables}
  • )} diff --git a/packages/query-core/src/mutation.ts b/packages/query-core/src/mutation.ts index 73e6c7f3f9b..6f28579ff88 100644 --- a/packages/query-core/src/mutation.ts +++ b/packages/query-core/src/mutation.ts @@ -30,6 +30,7 @@ export interface MutationState< isPaused: boolean status: MutationStatus variables: TVariables | undefined + submittedAt: number } interface FailedAction { @@ -271,6 +272,7 @@ export class Mutation< isPaused: !canFetch(this.options.networkMode), status: 'loading', variables: action.variables, + submittedAt: Date.now(), } case 'success': return { @@ -324,5 +326,6 @@ export function getDefaultState< isPaused: false, status: 'idle', variables: undefined, + submittedAt: 0, } } From 1d3b3bf3d069550ad2fd4fb879fba1a599702078 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Mon, 30 Jan 2023 16:27:25 +0100 Subject: [PATCH 48/60] fix a test --- packages/query-core/src/tests/mutations.test.tsx | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/query-core/src/tests/mutations.test.tsx b/packages/query-core/src/tests/mutations.test.tsx index 01b310867f6..0454955a7d1 100644 --- a/packages/query-core/src/tests/mutations.test.tsx +++ b/packages/query-core/src/tests/mutations.test.tsx @@ -268,6 +268,7 @@ describe('mutations', () => { isPaused: true, status: 'loading', variables: 'todo', + submittedAt: 1, }, ) @@ -280,6 +281,7 @@ describe('mutations', () => { isPaused: true, status: 'loading', variables: 'todo', + submittedAt: 1, }) await queryClient.resumePausedMutations() @@ -293,6 +295,7 @@ describe('mutations', () => { isPaused: false, status: 'success', variables: 'todo', + submittedAt: 1, }) expect(onMutate).not.toHaveBeenCalled() From 2191b3d094ca908fdb1173d20950484fd29d0db4 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Mon, 30 Jan 2023 16:34:46 +0100 Subject: [PATCH 49/60] test: add submittedAt to test assertions --- packages/query-core/src/tests/mutations.test.tsx | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/packages/query-core/src/tests/mutations.test.tsx b/packages/query-core/src/tests/mutations.test.tsx index 0454955a7d1..0dcb1019335 100644 --- a/packages/query-core/src/tests/mutations.test.tsx +++ b/packages/query-core/src/tests/mutations.test.tsx @@ -74,6 +74,7 @@ describe('mutations', () => { reset: expect.any(Function), status: 'idle', variables: undefined, + submittedAt: 0, }) const states: MutationState[] = [] @@ -101,6 +102,7 @@ describe('mutations', () => { reset: expect.any(Function), status: 'loading', variables: 'todo', + submittedAt: expect.any(Number), }) await sleep(5) @@ -120,6 +122,7 @@ describe('mutations', () => { reset: expect.any(Function), status: 'loading', variables: 'todo', + submittedAt: expect.any(Number), }) await sleep(20) @@ -139,6 +142,7 @@ describe('mutations', () => { reset: expect.any(Function), status: 'success', variables: 'todo', + submittedAt: expect.any(Number), }) }) @@ -178,6 +182,7 @@ describe('mutations', () => { reset: expect.any(Function), status: 'loading', variables: 'todo', + submittedAt: expect.any(Number), }) await sleep(10) @@ -197,6 +202,7 @@ describe('mutations', () => { reset: expect.any(Function), status: 'loading', variables: 'todo', + submittedAt: expect.any(Number), }) await sleep(20) @@ -216,6 +222,7 @@ describe('mutations', () => { reset: expect.any(Function), status: 'loading', variables: 'todo', + submittedAt: expect.any(Number), }) await sleep(30) @@ -235,6 +242,7 @@ describe('mutations', () => { reset: expect.any(Function), status: 'error', variables: 'todo', + submittedAt: expect.any(Number), }) }) From 1eeaf9dc0a53e28072181b335316821ac85266df Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Mon, 30 Jan 2023 17:28:25 +0100 Subject: [PATCH 50/60] docs: document new optimistic updates --- docs/react/guides/optimistic-updates.md | 95 +++++++++++++++++++++++-- 1 file changed, 88 insertions(+), 7 deletions(-) diff --git a/docs/react/guides/optimistic-updates.md b/docs/react/guides/optimistic-updates.md index 59aee308078..98f674deb03 100644 --- a/docs/react/guides/optimistic-updates.md +++ b/docs/react/guides/optimistic-updates.md @@ -3,11 +3,90 @@ id: optimistic-updates title: Optimistic Updates --- +React Query provides two ways to optimistically update your UI before a mutation has completed. You can either use the `onMutate` option to update your cache directly, or leverage the returned `variables` to update your UI from the `useMutation` result. + +## Via the UI + +This is the simpler variant, as it doesn't interact with the cache directly. + +[//]: # 'ExampleUI1' +```tsx + const { isPending, submittedAt, variables, mutate, isError } = useMutation({ + mutationFn: (newTodo: string) => axios.post('/api/data', { text: newTodo }), + // make sure to _return_ the Promise from the query invalidation + // so that the mutation stays in `pending` state until the refetch is finished + onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), + }) +``` +[//]: # 'ExampleUI1' + +you will then have access to `addTodoMutation.variables`, which contain the added todo. In your UI list, where the query is rendered, you can append another item to the list while the mutation is `pending`: + +[//]: # 'ExampleUI2' +```tsx +
      + {todoQuery.items.map((todo) => ( +
    • {todo.text}
    • + ))} + {isPending && ( +
    • + {variables} +
    • + )} +
    +``` +[//]: # 'ExampleUI2' + +The `submittedAt` property is a timestamp that is set when `mutate` is invoked. This is useful to create a unique key for the pending todo item. We've also added an `opacity` to indicate that this item is only temporarily here. Once the mutation completes, the item will be removed because the mutation is no longer `pending`. Given that the refetch succeeded, we should see the item as a "normal item" in our list. + +If the mutation errors, the item will also disappear. But we could continue to show it, if we want, by checking for the `isError` state of the mutation. `variables` are _not_ cleared when the mutation errors, so we can still access them, maybe even show a retry button: + +[//]: # 'ExampleUI3' +```tsx +{isError && ( +
  • + {variables} + +
  • +)} +``` +[//]: # 'ExampleUI3' + +### If the mutation and the query don't live in the same component + +This approach works very will if the mutation and the query live in the same component, However, you also get access to running mutations in other components via the dedicated `useMutationVariables` hook. It is best combined with a `mutationKey`: + +[//]: # 'ExampleUI4' +```tsx +// somewhere in your app +const { mutate } = useMutation({ + mutationFn: (newTodo: string) => axios.post('/api/data', { text: newTodo }), + onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), + mutationKey: ['addTodo'] +}) + +// access variables somewhere else +const { variables } = useMutationVariables({ mutationKey: ['addTodo'], status: 'pending' }) +``` +[//]: # 'ExampleUI4' + +`variables` will be an `Array`, because there might be multiple mutations running at the same time. This will even make displaying concurrent optimistic updates a breeze. + +## Via the cache + When you optimistically update your state before performing a mutation, there is a chance that the mutation will fail. In most of these failure cases, you can just trigger a refetch for your optimistic queries to revert them to their true server state. In some circumstances though, refetching may not work correctly and the mutation error could represent some type of server issue that won't make it possible to refetch. In this event, you can instead choose to rollback your update. To do this, `useMutation`'s `onMutate` handler option allows you to return a value that will later be passed to both `onError` and `onSettled` handlers as the last argument. In most cases, it is most useful to pass a rollback function. -## Updating a list of todos when adding a new todo +### Updating a list of todos when adding a new todo [//]: # 'Example' @@ -42,13 +121,11 @@ useMutation({ }, }) ``` - [//]: # 'Example' -## Updating a single todo +### Updating a single todo [//]: # 'Example2' - ```tsx useMutation({ mutationFn: updateTodo, @@ -80,13 +157,11 @@ useMutation({ }, }) ``` - [//]: # 'Example2' You can also use the `onSettled` function in place of the separate `onError` and `onSuccess` handlers if you wish: [//]: # 'Example3' - ```tsx useMutation({ mutationFn: updateTodo, @@ -98,5 +173,11 @@ useMutation({ }, }) ``` - [//]: # 'Example3' + + +## When to use what + +If you only have one place where the optimistic result should be shown, using `variables` and updating the UI directly is the approach that requires less code and is generally easier to reason about. For example, you don't need to handle rollbacks at all. + +However, if you have multiple places on the screen that would require to know about the update, manipulating the cache directly will take care of this for you automatically. From e61d86cb540b757834606f6f71ada834094c7f55 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Mon, 30 Jan 2023 17:29:21 +0100 Subject: [PATCH 51/60] docs: add `isError` check to optimistic updates example --- .../optimistic-updates-typescript/pages/index.tsx | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/examples/react/optimistic-updates-typescript/pages/index.tsx b/examples/react/optimistic-updates-typescript/pages/index.tsx index f236f7256e2..05f3ad61528 100755 --- a/examples/react/optimistic-updates-typescript/pages/index.tsx +++ b/examples/react/optimistic-updates-typescript/pages/index.tsx @@ -82,6 +82,21 @@ function Example() { {addTodoMutation.variables} )} + {addTodoMutation.isError && ( +
  • + {addTodoMutation.variables} + +
  • + )} {isFetching &&
    Updating in background...
    } From c02cab800c4dba8d0499f2b187361d8b88f8f052 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Mon, 30 Jan 2023 17:32:35 +0100 Subject: [PATCH 52/60] feat: replace isFetching with status for mutationFilters --- docs/react/guides/filters.md | 5 ++--- packages/query-core/src/queryClient.ts | 2 +- packages/query-core/src/utils.ts | 19 +++++++++++-------- .../src/__tests__/useMutationState.test.tsx | 2 +- 4 files changed, 15 insertions(+), 13 deletions(-) diff --git a/docs/react/guides/filters.md b/docs/react/guides/filters.md index e1588cd3aa8..c55d8f93012 100644 --- a/docs/react/guides/filters.md +++ b/docs/react/guides/filters.md @@ -66,8 +66,7 @@ A mutation filter object supports the following properties: - Set this property to define a mutation key to match on. - `exact?: boolean` - If you don't want to search mutations inclusively by mutation key, you can pass the `exact: true` option to return only the mutation with the exact mutation key you have passed. -- `fetching?: boolean` - - When set to `true` it will match mutations that are currently fetching. - - When set to `false` it will match mutations that are not fetching. +- `status?: MutationStatus` + - Allows for filtering mutations according to their status. - `predicate?: (mutation: Mutation) => boolean` - This predicate function will be used as a final filter on all matching mutations. If no other filters are specified, this function will be evaluated against every mutation in the cache. diff --git a/packages/query-core/src/queryClient.ts b/packages/query-core/src/queryClient.ts index e27f9acfb25..e13c87f53f3 100644 --- a/packages/query-core/src/queryClient.ts +++ b/packages/query-core/src/queryClient.ts @@ -103,7 +103,7 @@ export class QueryClient { } isMutating(filters?: MutationFilters): number { - return this.#mutationCache.findAll({ ...filters, fetching: true }).length + return this.#mutationCache.findAll({ ...filters, status: 'loading' }).length } getMutationVariables( diff --git a/packages/query-core/src/utils.ts b/packages/query-core/src/utils.ts index 9c18f71bf16..39211234cac 100644 --- a/packages/query-core/src/utils.ts +++ b/packages/query-core/src/utils.ts @@ -1,6 +1,12 @@ import type { Mutation } from './mutation' import type { Query } from './query' -import type { FetchStatus, MutationKey, QueryKey, QueryOptions } from './types' +import type { + FetchStatus, + MutationKey, + MutationStatus, + QueryKey, + QueryOptions, +} from './types' // TYPES @@ -45,9 +51,9 @@ export interface MutationFilters { */ mutationKey?: MutationKey /** - * Include or exclude fetching mutations + * Filter by mutation status */ - fetching?: boolean + status?: MutationStatus } export type DataUpdateFunction = (input: TInput) => TOutput @@ -138,7 +144,7 @@ export function matchMutation( filters: MutationFilters, mutation: Mutation, ): boolean { - const { exact, fetching, predicate, mutationKey } = filters + const { exact, status, predicate, mutationKey } = filters if (mutationKey) { if (!mutation.options.mutationKey) { return false @@ -152,10 +158,7 @@ export function matchMutation( } } - if ( - typeof fetching === 'boolean' && - (mutation.state.status === 'loading') !== fetching - ) { + if (status && mutation.state.status !== status) { return false } diff --git a/packages/react-query/src/__tests__/useMutationState.test.tsx b/packages/react-query/src/__tests__/useMutationState.test.tsx index bba0a81595e..dc983525322 100644 --- a/packages/react-query/src/__tests__/useMutationState.test.tsx +++ b/packages/react-query/src/__tests__/useMutationState.test.tsx @@ -236,7 +236,7 @@ describe('useMutationVariables', () => { function Variables() { variables.push( - useMutationVariables({ mutationKey, fetching: true }), + useMutationVariables({ mutationKey, status: 'loading' }), ) return null From f6eb91ee765e421979cb89dec5f1da215005a14e Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Mon, 30 Jan 2023 17:39:25 +0100 Subject: [PATCH 53/60] fix: make sure TVariables narrow correctly --- packages/query-core/src/types.ts | 4 +-- .../src/__tests__/useMutation.types.test.tsx | 27 +++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/packages/query-core/src/types.ts b/packages/query-core/src/types.ts index 68ae280dea9..da52392e842 100644 --- a/packages/query-core/src/types.ts +++ b/packages/query-core/src/types.ts @@ -673,7 +673,7 @@ export interface MutationObserverErrorResult< > extends MutationObserverBaseResult { data: undefined error: TError - variables: undefined + variables: TVariables isError: true isIdle: false isLoading: false @@ -689,7 +689,7 @@ export interface MutationObserverSuccessResult< > extends MutationObserverBaseResult { data: TData error: null - variables: undefined + variables: TVariables isError: false isIdle: false isLoading: false diff --git a/packages/vue-query/src/__tests__/useMutation.types.test.tsx b/packages/vue-query/src/__tests__/useMutation.types.test.tsx index ccfe84671e7..f4c37c6f87a 100644 --- a/packages/vue-query/src/__tests__/useMutation.types.test.tsx +++ b/packages/vue-query/src/__tests__/useMutation.types.test.tsx @@ -71,4 +71,31 @@ describe('Discriminated union return type', () => { return }) }) + + it('should narrow variables', () => { + doNotExecute(() => { + const mutation = reactive( + useMutation({ mutationFn: successMutator }), + ) + + if (mutation.isIdle) { + const result: Expect> = true + return result + } + if (mutation.isLoading) { + const result: Expect> = true + return result + } + if (mutation.isSuccess) { + const result: Expect> = true + return result + } + if (mutation.isError) { + const result: Expect> = true + return result + } + + return + }) + }) }) From 3563147a31b2dcc48973e963b6037e30ebea2857 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Sun, 12 Feb 2023 14:40:29 +0100 Subject: [PATCH 54/60] formatting --- packages/query-core/src/mutation.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/packages/query-core/src/mutation.ts b/packages/query-core/src/mutation.ts index 13bceda5e1f..1e73baabac6 100644 --- a/packages/query-core/src/mutation.ts +++ b/packages/query-core/src/mutation.ts @@ -147,8 +147,11 @@ export class Mutation< } continue(): Promise { - // continuing a mutation assumes that variables are set, mutation must have been dehydrated before - return this.#retryer?.continue() ?? this.execute(this.state.variables!) + return ( + this.#retryer?.continue() ?? + // continuing a mutation assumes that variables are set, mutation must have been dehydrated before + this.execute(this.state.variables!) + ) } async execute(variables: TVariables): Promise { From 78509ef59730976973e0a5085ae0ec339f15de61 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Sun, 12 Feb 2023 14:54:08 +0100 Subject: [PATCH 55/60] stabilize a flaky test --- .../src/__tests__/createQuery.test.tsx | 21 ++++++++++--------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/packages/solid-query/src/__tests__/createQuery.test.tsx b/packages/solid-query/src/__tests__/createQuery.test.tsx index 8b76cc9a48c..fd56c257372 100644 --- a/packages/solid-query/src/__tests__/createQuery.test.tsx +++ b/packages/solid-query/src/__tests__/createQuery.test.tsx @@ -1094,7 +1094,10 @@ describe('createQuery', () => { function Page() { const state = createQuery(() => ({ queryKey: key, - queryFn: () => ({ name: 'test' }), + queryFn: async () => { + await sleep(10) + return { name: 'test' } + }, select: (data) => data.name, notifyOnChangeProps: ['data'], })) @@ -1103,14 +1106,12 @@ describe('createQuery', () => { states.push({ ...state }) }) - createEffect(() => { - const refetch = state.refetch - setActTimeout(() => { - refetch() - }, 5) - }) - - return null + return ( +
    + data: {state.data} + +
    + ) } render(() => ( @@ -1119,7 +1120,7 @@ describe('createQuery', () => { )) - await sleep(10) + await waitFor(() => screen.getByText('data: test')) expect(states.length).toBe(2) expect(states[0]).toMatchObject({ data: undefined }) From 175f8d0cdb6973fd20dc96a1973261094e7cbad4 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Sun, 12 Feb 2023 17:20:39 +0100 Subject: [PATCH 56/60] expose useMutationState instead of useMutationVariables, which can be implemented with useMutationState --- packages/query-core/src/queryClient.ts | 7 --- .../src/__tests__/useMutationState.test.tsx | 9 ++- packages/react-query/src/useMutationState.ts | 56 ++++++++++++++----- 3 files changed, 48 insertions(+), 24 deletions(-) diff --git a/packages/query-core/src/queryClient.ts b/packages/query-core/src/queryClient.ts index 9af1b024848..81c81f72868 100644 --- a/packages/query-core/src/queryClient.ts +++ b/packages/query-core/src/queryClient.ts @@ -107,13 +107,6 @@ export class QueryClient { return this.#mutationCache.findAll({ ...filters, status: 'loading' }).length } - getMutationVariables( - filters?: MutationFilters, - ): TVariables[] { - return this.#mutationCache - .findAll(filters) - .map((mutation) => mutation.state.variables as unknown as TVariables) - } getQueryData( queryKey: QueryKey, ): TQueryFnData | undefined { diff --git a/packages/react-query/src/__tests__/useMutationState.test.tsx b/packages/react-query/src/__tests__/useMutationState.test.tsx index dc983525322..e85c3e363db 100644 --- a/packages/react-query/src/__tests__/useMutationState.test.tsx +++ b/packages/react-query/src/__tests__/useMutationState.test.tsx @@ -1,6 +1,6 @@ import { fireEvent, render, waitFor } from '@testing-library/react' import * as React from 'react' -import { useIsMutating, useMutationVariables } from '../useMutationState' +import { useIsMutating, useMutationState } from '../useMutationState' import { useMutation } from '../useMutation' import { createQueryClient, @@ -231,12 +231,15 @@ describe('useIsMutating', () => { describe('useMutationVariables', () => { it('should return variables after calling mutate', async () => { const queryClient = createQueryClient() - const variables: number[][] = [] + const variables: unknown[][] = [] const mutationKey = ['mutation'] function Variables() { variables.push( - useMutationVariables({ mutationKey, status: 'loading' }), + useMutationState({ + filters: { mutationKey, status: 'loading' }, + select: (mutation) => mutation.state.variables, + }), ) return null diff --git a/packages/react-query/src/useMutationState.ts b/packages/react-query/src/useMutationState.ts index c63596f571c..631feaef5b2 100644 --- a/packages/react-query/src/useMutationState.ts +++ b/packages/react-query/src/useMutationState.ts @@ -1,35 +1,63 @@ import * as React from 'react' -import type { MutationFilters, QueryClient } from '@tanstack/query-core' +import type { + MutationFilters, + QueryClient, + Mutation, + MutationCache, + RegisteredError, +} from '@tanstack/query-core' import { notifyManager, replaceEqualDeep } from '@tanstack/query-core' import { useQueryClient } from './QueryClientProvider' +import type { MutationState } from '@tanstack/query-core/build/lib/mutation' export function useIsMutating( filters?: MutationFilters, queryClient?: QueryClient, ): number { const client = useQueryClient(queryClient) - return useMutationState(() => client.isMutating(filters), client) + return useMutationState( + { filters: { ...filters, status: 'loading' } }, + client, + ).length } -export function useMutationVariables( - filters?: MutationFilters, - queryClient?: QueryClient, -): Array { - const client = useQueryClient(queryClient) - return useMutationState(() => client.getMutationVariables(filters), client) +type MutationStateOptions = { + filters?: MutationFilters + select?: ( + mutation: Mutation, + ) => TResult } -function useMutationState(selector: () => T, queryClient?: QueryClient): T { +function getResult( + mutationCache: MutationCache, + options: MutationStateOptions, +): Array { + return mutationCache + .findAll(options.filters) + .map( + (mutation): TResult => + (options.select + ? options.select( + mutation as Mutation, + ) + : mutation.state) as TResult, + ) +} + +export function useMutationState( + options: MutationStateOptions = {}, + queryClient?: QueryClient, +): Array { const mutationCache = useQueryClient(queryClient).getMutationCache() - const selectorRef = React.useRef(selector) - const result = React.useRef() + const optionsRef = React.useRef(options) + const result = React.useRef>() if (!result.current) { - result.current = selector() + result.current = getResult(mutationCache, options) } React.useEffect(() => { - selectorRef.current = selector + optionsRef.current = options }) return React.useSyncExternalStore( @@ -38,7 +66,7 @@ function useMutationState(selector: () => T, queryClient?: QueryClient): T { mutationCache.subscribe(() => { const nextResult = replaceEqualDeep( result.current, - selectorRef.current(), + getResult(mutationCache, optionsRef.current), ) if (result.current !== nextResult) { result.current = nextResult From b98c96ce4f7c59241e7ae21a8a7cf6fe460f69bd Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Sun, 12 Feb 2023 17:38:47 +0100 Subject: [PATCH 57/60] docs update --- docs/config.json | 4 +++ docs/react/devtools.md | 4 +-- docs/react/guides/optimistic-updates.md | 7 ++-- docs/react/reference/QueryClientProvider.md | 2 -- docs/react/reference/hydration.md | 8 ++--- docs/react/reference/useIsFetching.md | 4 +-- docs/react/reference/useIsMutating.md | 4 +-- docs/react/reference/useMutation.md | 4 +-- docs/react/reference/useMutationState.md | 35 +++++++++++++++++++ docs/react/reference/useQueries.md | 4 +-- docs/react/reference/useQuery.md | 4 +-- docs/react/reference/useQueryClient.md | 6 ++-- .../src/__tests__/useMutationState.test.tsx | 2 +- packages/react-query/src/index.ts | 2 +- 14 files changed, 65 insertions(+), 25 deletions(-) create mode 100644 docs/react/reference/useMutationState.md diff --git a/docs/config.json b/docs/config.json index f7ed6c171e6..63cc06f69b4 100644 --- a/docs/config.json +++ b/docs/config.json @@ -341,6 +341,10 @@ "label": "useIsMutating", "to": "react/reference/useIsMutating" }, + { + "label": "useMutationState", + "to": "react/reference/useMutationState" + }, { "label": "QueryClient", "to": "react/reference/QueryClient" diff --git a/docs/react/devtools.md b/docs/react/devtools.md index 54984d7fa1e..6bdea377fca 100644 --- a/docs/react/devtools.md +++ b/docs/react/devtools.md @@ -66,8 +66,8 @@ function App() { - `panelPosition?: "top" | "bottom" | "left" | "right"` - Defaults to `bottom` - The position of the React Query devtools panel -- `context?: React.Context` - - Use this to use a custom React Query context. Otherwise, `defaultContext` will be used. +- `queryClient?: QueryClient`, + - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used. ## Embedded Mode diff --git a/docs/react/guides/optimistic-updates.md b/docs/react/guides/optimistic-updates.md index 98f674deb03..67a4fc8ef72 100644 --- a/docs/react/guides/optimistic-updates.md +++ b/docs/react/guides/optimistic-updates.md @@ -62,7 +62,7 @@ If the mutation errors, the item will also disappear. But we could continue to s ### If the mutation and the query don't live in the same component -This approach works very will if the mutation and the query live in the same component, However, you also get access to running mutations in other components via the dedicated `useMutationVariables` hook. It is best combined with a `mutationKey`: +This approach works very will if the mutation and the query live in the same component, However, you also get access to all mutations in other components via the dedicated `useMurationState` hook. It is best combined with a `mutationKey`: [//]: # 'ExampleUI4' ```tsx @@ -74,7 +74,10 @@ const { mutate } = useMutation({ }) // access variables somewhere else -const { variables } = useMutationVariables({ mutationKey: ['addTodo'], status: 'pending' }) +const variables = useMutationState({ + filters: { mutationKey: ['addTodo'], status: 'pending' }, + select: (mutation) => mutation.state.variables +}) ``` [//]: # 'ExampleUI4' diff --git a/docs/react/reference/QueryClientProvider.md b/docs/react/reference/QueryClientProvider.md index f0be794d89b..08d6d9ec321 100644 --- a/docs/react/reference/QueryClientProvider.md +++ b/docs/react/reference/QueryClientProvider.md @@ -20,5 +20,3 @@ function App() { - `client: QueryClient` - **Required** - the QueryClient instance to provide -- `context?: React.Context` - - Use this to use a custom React Query context. Otherwise, `defaultContext` will be used. diff --git a/docs/react/reference/hydration.md b/docs/react/reference/hydration.md index 7e1c17f41f8..ee657a37cb7 100644 --- a/docs/react/reference/hydration.md +++ b/docs/react/reference/hydration.md @@ -86,8 +86,8 @@ hydrate(queryClient, dehydratedState, options) - Optional - `mutations: MutationOptions` The default mutation options to use for the hydrated mutations. - `queries: QueryOptions` The default query options to use for the hydrated queries. - - `context?: React.Context` - - Use this to use a custom React Query context. Otherwise, `defaultContext` will be used. + - `queryClient?: QueryClient`, + - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used. ### Limitations @@ -115,7 +115,7 @@ function App() { - Optional - `defaultOptions: QueryOptions` - The default query options to use for the hydrated queries. - - `context?: React.Context` - - Use this to use a custom React Query context. Otherwise, `defaultContext` will be used. + - `queryClient?: QueryClient`, + - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used. [//]: # 'HydrationBoundary' diff --git a/docs/react/reference/useIsFetching.md b/docs/react/reference/useIsFetching.md index 19b3fe0116a..d35a06a67e1 100644 --- a/docs/react/reference/useIsFetching.md +++ b/docs/react/reference/useIsFetching.md @@ -16,8 +16,8 @@ const isFetchingPosts = useIsFetching({ queryKey: ['posts'] }) **Options** - `filters?: QueryFilters`: [Query Filters](../guides/filters#query-filters) -- `context?: React.Context` - - Use this to use a custom React Query context. Otherwise, `defaultContext` will be used. +- `queryClient?: QueryClient`, + - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used. **Returns** diff --git a/docs/react/reference/useIsMutating.md b/docs/react/reference/useIsMutating.md index 0897fb3438e..7ad18498912 100644 --- a/docs/react/reference/useIsMutating.md +++ b/docs/react/reference/useIsMutating.md @@ -16,8 +16,8 @@ const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] }) **Options** - `filters?: MutationFilters`: [Mutation Filters](../guides/filters#mutation-filters) -- `context?: React.Context` - - Use this to use a custom React Query context. Otherwise, `defaultContext` will be used. +- `queryClient?: QueryClient`, + - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used. **Returns** diff --git a/docs/react/reference/useMutation.md b/docs/react/reference/useMutation.md index 5cb0f0cdabf..73c049a9f05 100644 --- a/docs/react/reference/useMutation.md +++ b/docs/react/reference/useMutation.md @@ -91,8 +91,8 @@ mutate(variables, { - `meta: Record` - Optional - If set, stores additional information on the mutation cache entry that can be used as needed. It will be accessible wherever the `mutation` is available (eg. `onError`, `onSuccess` functions of the `MutationCache`). -- `context?: React.Context` - - Use this to use a custom React Query context. Otherwise, `defaultContext` will be used. +- `queryClient?: QueryClient`, + - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used. **Returns** diff --git a/docs/react/reference/useMutationState.md b/docs/react/reference/useMutationState.md new file mode 100644 index 00000000000..1850cf2b613 --- /dev/null +++ b/docs/react/reference/useMutationState.md @@ -0,0 +1,35 @@ +--- +id: useMutationState +title: useMutationState +--- + +`useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass `filters` to it to narrow down your mutations, and `select` to transform the mutation state. + +```tsx +import { useMutationState } from '@tanstack/react-query' +// Get all variables of all running mutations +const variables = useMutationState({ + filters: { status: 'pending' }, + select: (mutation) => mutation.state.variables, +}) + +// Get all data of all "post" mutations +const data = useMutationState({ + filters: { mutationKey: ['posts'] }, + select: (mutation) => mutation.state.data, +}) +``` + +**Options** + +- `options` + - `filters?: MutationFilters`: [Mutation Filters](../guides/filters#mutation-filters) + - `select?: (mutation: Mutation) => TResult` + - Use this to transform the mutation state. +- `queryClient?: QueryClient`, + - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used. + +**Returns** + +- `Array` + - Will be an Array of whatever `select` returns for each matching mutation. diff --git a/docs/react/reference/useQueries.md b/docs/react/reference/useQueries.md index bb203961e48..87e6344e8d0 100644 --- a/docs/react/reference/useQueries.md +++ b/docs/react/reference/useQueries.md @@ -18,8 +18,8 @@ const results = useQueries({ The `useQueries` hook accepts an options object with a **queries** key whose value is an array with query option objects identical to the [`useQuery` hook](../reference/useQuery) (excluding the `context` option). -- `context?: React.Context` - - Use this to use a custom React Query context. Otherwise, `defaultContext` will be used. +- `queryClient?: QueryClient`, + - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used. > Having the same query key more than once in the array of query objects may cause some data to be shared between queries, e.g. when using `placeholderData` and `select`. To avoid this, consider de-duplicating the queries and map the results back to the desired structure. diff --git a/docs/react/reference/useQuery.md b/docs/react/reference/useQuery.md index 87b478c2068..1ef5296af97 100644 --- a/docs/react/reference/useQuery.md +++ b/docs/react/reference/useQuery.md @@ -177,8 +177,8 @@ const { - `meta: Record` - Optional - If set, stores additional information on the query cache entry that can be used as needed. It will be accessible wherever the `query` is available, and is also part of the `QueryFunctionContext` provided to the `queryFn`. -- `context?: React.Context` - - Use this to use a custom React Query context. Otherwise, `defaultContext` will be used. +- `queryClient?: QueryClient`, + - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used. **Returns** diff --git a/docs/react/reference/useQueryClient.md b/docs/react/reference/useQueryClient.md index 36091b33224..e3b55206f70 100644 --- a/docs/react/reference/useQueryClient.md +++ b/docs/react/reference/useQueryClient.md @@ -8,10 +8,10 @@ The `useQueryClient` hook returns the current `QueryClient` instance. ```tsx import { useQueryClient } from '@tanstack/react-query' -const queryClient = useQueryClient({ context }) +const queryClient = useQueryClient(queryClient?: QueryClient) ``` **Options** -- `context?: React.Context` - - Use this to use a custom React Query context. Otherwise, `defaultContext` will be used. +- `queryClient?: QueryClient`, + - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used. diff --git a/packages/react-query/src/__tests__/useMutationState.test.tsx b/packages/react-query/src/__tests__/useMutationState.test.tsx index e85c3e363db..0c4886beff5 100644 --- a/packages/react-query/src/__tests__/useMutationState.test.tsx +++ b/packages/react-query/src/__tests__/useMutationState.test.tsx @@ -228,7 +228,7 @@ describe('useIsMutating', () => { }) }) -describe('useMutationVariables', () => { +describe('useMutationState', () => { it('should return variables after calling mutate', async () => { const queryClient = createQueryClient() const variables: unknown[][] = [] diff --git a/packages/react-query/src/index.ts b/packages/react-query/src/index.ts index abd5e810043..b4e09103441 100644 --- a/packages/react-query/src/index.ts +++ b/packages/react-query/src/index.ts @@ -22,7 +22,7 @@ export { useQueryErrorResetBoundary, } from './QueryErrorResetBoundary' export { useIsFetching } from './useIsFetching' -export { useIsMutating, useMutationVariables } from './useMutationState' +export { useIsMutating, useMutationState } from './useMutationState' export { useMutation } from './useMutation' export { useInfiniteQuery } from './useInfiniteQuery' export { useIsRestoring, IsRestoringProvider } from './isRestoring' From c733726d0dd6d0086dac0aa36b56bd78cfb4ae75 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Sat, 18 Feb 2023 12:57:25 +0100 Subject: [PATCH 58/60] fix: status 'loading' is no longer a thing it needs to be `'pending'` everywhere --- examples/react/auto-refetching/pages/index.js | 2 +- examples/react/infinite-query-with-max-pages/pages/index.js | 4 ++-- examples/react/load-more-infinite-scroll/pages/index.js | 6 +++--- examples/react/pagination/pages/index.js | 4 ++-- examples/react/prefetching/pages/[user]/[repo].js | 2 +- examples/solid/basic-graphql-request/src/index.tsx | 4 ++-- examples/solid/basic-typescript/src/index.tsx | 4 ++-- examples/solid/default-query-function/src/index.tsx | 4 ++-- examples/svelte/basic/src/lib/Posts.svelte | 2 +- examples/svelte/playground/src/routes/AddTodo.svelte | 6 +++--- examples/svelte/playground/src/routes/EditTodo.svelte | 6 +++--- examples/svelte/playground/src/routes/Todos.svelte | 2 +- examples/svelte/ssr/src/lib/Posts.svelte | 2 +- .../svelte/star-wars/src/routes/characters/+page.svelte | 2 +- .../src/routes/characters/[characterId]/+page.svelte | 2 +- examples/svelte/star-wars/src/routes/films/+page.svelte | 2 +- .../svelte/star-wars/src/routes/films/[filmId]/+page.svelte | 2 +- packages/query-core/src/queryClient.ts | 2 +- packages/query-core/src/types.ts | 2 +- .../react-query/src/__tests__/useMutationState.test.tsx | 2 +- packages/react-query/src/useMutationState.ts | 2 +- 21 files changed, 32 insertions(+), 32 deletions(-) diff --git a/examples/react/auto-refetching/pages/index.js b/examples/react/auto-refetching/pages/index.js index 22f36954b26..09831ec7d87 100755 --- a/examples/react/auto-refetching/pages/index.js +++ b/examples/react/auto-refetching/pages/index.js @@ -47,7 +47,7 @@ function Example() { onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), }) - if (status === 'loading') return

    Loading...

    + if (status === 'pending') return

    Loading...

    if (status === 'error') return Error: {error.message} return ( diff --git a/examples/react/infinite-query-with-max-pages/pages/index.js b/examples/react/infinite-query-with-max-pages/pages/index.js index 99c730f7909..4c520a8de53 100755 --- a/examples/react/infinite-query-with-max-pages/pages/index.js +++ b/examples/react/infinite-query-with-max-pages/pages/index.js @@ -45,7 +45,7 @@ function Example() {

    Infinite Query with max pages

    4 projects per page

    3 pages max

    - {status === 'loading' ? ( + {status === 'pending' ? (

    Loading...

    ) : status === 'error' ? ( Error: {error.message} @@ -63,7 +63,7 @@ function Example() { : 'Nothing more to load'}
    - {data?.pages.map((page) => ( + {data.pages.map((page) => ( {page.data.map((project) => (

    Infinite Loading

    - {status === 'loading' ? ( + {status === 'pending' ? (

    Loading...

    ) : status === 'error' ? ( Error: {error.message} diff --git a/examples/react/pagination/pages/index.js b/examples/react/pagination/pages/index.js index 41693acfffd..6206f8547fd 100644 --- a/examples/react/pagination/pages/index.js +++ b/examples/react/pagination/pages/index.js @@ -55,7 +55,7 @@ function Example() { instantaneously while they are also refetched invisibly in the background.

    - {status === 'loading' ? ( + {status === 'pending' ? (
    Loading...
    ) : status === 'error' ? (
    Error: {error.message}
    @@ -86,7 +86,7 @@ function Example() { { // Since the last page's data potentially sticks around between page requests, // we can use `isFetching` to show a background loading - // indicator since our `status === 'loading'` state won't be triggered + // indicator since our `status === 'pending'` state won't be triggered isFetching ? Loading... : null }{' '} diff --git a/examples/react/prefetching/pages/[user]/[repo].js b/examples/react/prefetching/pages/[user]/[repo].js index 33c3253ef97..4045cc6dde1 100755 --- a/examples/react/prefetching/pages/[user]/[repo].js +++ b/examples/react/prefetching/pages/[user]/[repo].js @@ -16,7 +16,7 @@ export default () => { return (

    {id}

    - {status === 'loading' ? ( + {status === 'pending' ? ( 'Loading...' ) : status === 'error' ? ( Error: {error.message} diff --git a/examples/solid/basic-graphql-request/src/index.tsx b/examples/solid/basic-graphql-request/src/index.tsx index b8f8eb3abab..9e52205dd8c 100644 --- a/examples/solid/basic-graphql-request/src/index.tsx +++ b/examples/solid/basic-graphql-request/src/index.tsx @@ -69,7 +69,7 @@ function Posts(props: { setPostId: Setter }) {

    Posts

    - Loading... + Loading... Error: {(state.error as Error).message} @@ -142,7 +142,7 @@ function Post(props: { postId: number; setPostId: Setter }) {
    - + Loading... diff --git a/examples/solid/basic-typescript/src/index.tsx b/examples/solid/basic-typescript/src/index.tsx index 1334ac9a53c..52bd01994ce 100644 --- a/examples/solid/basic-typescript/src/index.tsx +++ b/examples/solid/basic-typescript/src/index.tsx @@ -45,7 +45,7 @@ function Posts(props: { setPostId: Setter }) {

    Posts

    - Loading... + Loading... Error: {(state.error as Error).message} @@ -113,7 +113,7 @@ function Post(props: { postId: number; setPostId: Setter }) {
    - + Loading... diff --git a/examples/solid/default-query-function/src/index.tsx b/examples/solid/default-query-function/src/index.tsx index d70b15dfe14..a2b6ccf3d74 100644 --- a/examples/solid/default-query-function/src/index.tsx +++ b/examples/solid/default-query-function/src/index.tsx @@ -60,7 +60,7 @@ function Posts(props: { setPostId: Setter }) {

    Posts

    - Loading... + Loading... Error: {(state.error as Error).message} @@ -114,7 +114,7 @@ function Post(props: { postId: number; setPostId: Setter }) {
    - + Loading... diff --git a/examples/svelte/basic/src/lib/Posts.svelte b/examples/svelte/basic/src/lib/Posts.svelte index 83b4112f66b..c4f2f2c6427 100644 --- a/examples/svelte/basic/src/lib/Posts.svelte +++ b/examples/svelte/basic/src/lib/Posts.svelte @@ -17,7 +17,7 @@
    - {#if $posts.status === 'loading'} + {#if $posts.status === 'pending'} Loading... {:else if $posts.status === 'error'} Error: {$posts.error.message} diff --git a/examples/svelte/playground/src/routes/AddTodo.svelte b/examples/svelte/playground/src/routes/AddTodo.svelte index c92fc2e47f7..88a71b7cf32 100644 --- a/examples/svelte/playground/src/routes/AddTodo.svelte +++ b/examples/svelte/playground/src/routes/AddTodo.svelte @@ -38,17 +38,17 @@
    - +
    - {$addMutation.status === 'loading' + {$addMutation.status === 'pending' ? 'Saving...' : $addMutation.status === 'error' ? $addMutation.error.message diff --git a/examples/svelte/playground/src/routes/EditTodo.svelte b/examples/svelte/playground/src/routes/EditTodo.svelte index fdf249a3349..24d7992e009 100644 --- a/examples/svelte/playground/src/routes/EditTodo.svelte +++ b/examples/svelte/playground/src/routes/EditTodo.svelte @@ -70,7 +70,7 @@ } $: disableEditSave = - $query.status === 'loading' || $saveMutation.status === 'loading' + $query.status === 'pending' || $saveMutation.status === 'pending'
    @@ -80,7 +80,7 @@ "{$query.data.name}" (#{$editingIndex}) {/if}
    - {#if $query.status === 'loading'} + {#if $query.status === 'pending'} Loading... (Attempt: {$query.failureCount + 1}) {:else if $query.error} @@ -99,7 +99,7 @@
    - {$saveMutation.status === 'loading' + {$saveMutation.status === 'pending' ? 'Saving...' : $saveMutation.status === 'error' ? $saveMutation.error.message diff --git a/examples/svelte/playground/src/routes/Todos.svelte b/examples/svelte/playground/src/routes/Todos.svelte index f3537d7c50f..1346fa722e2 100644 --- a/examples/svelte/playground/src/routes/Todos.svelte +++ b/examples/svelte/playground/src/routes/Todos.svelte @@ -40,7 +40,7 @@
    -{#if $query.status === 'loading'} +{#if $query.status === 'pending'} Loading... (Attempt: {$query.failureCount + 1}) {:else if $query.status === 'error'} diff --git a/examples/svelte/ssr/src/lib/Posts.svelte b/examples/svelte/ssr/src/lib/Posts.svelte index 83b4112f66b..c4f2f2c6427 100644 --- a/examples/svelte/ssr/src/lib/Posts.svelte +++ b/examples/svelte/ssr/src/lib/Posts.svelte @@ -17,7 +17,7 @@
    - {#if $posts.status === 'loading'} + {#if $posts.status === 'pending'} Loading... {:else if $posts.status === 'error'} Error: {$posts.error.message} diff --git a/examples/svelte/star-wars/src/routes/characters/+page.svelte b/examples/svelte/star-wars/src/routes/characters/+page.svelte index 77f868d693f..0fef65bd7a1 100644 --- a/examples/svelte/star-wars/src/routes/characters/+page.svelte +++ b/examples/svelte/star-wars/src/routes/characters/+page.svelte @@ -12,7 +12,7 @@ }) -{#if $query.status === 'loading'} +{#if $query.status === 'pending'}

    Loading...

    {/if} diff --git a/examples/svelte/star-wars/src/routes/characters/[characterId]/+page.svelte b/examples/svelte/star-wars/src/routes/characters/[characterId]/+page.svelte index 624ee7dece4..6743ccbcb5f 100644 --- a/examples/svelte/star-wars/src/routes/characters/[characterId]/+page.svelte +++ b/examples/svelte/star-wars/src/routes/characters/[characterId]/+page.svelte @@ -19,7 +19,7 @@ }) -{#if $query.status === 'loading'} +{#if $query.status === 'pending'}

    Loading...

    {/if} diff --git a/examples/svelte/star-wars/src/routes/films/+page.svelte b/examples/svelte/star-wars/src/routes/films/+page.svelte index 3a7cb247130..adb251e0d23 100644 --- a/examples/svelte/star-wars/src/routes/films/+page.svelte +++ b/examples/svelte/star-wars/src/routes/films/+page.svelte @@ -12,7 +12,7 @@ }) -{#if $query.status === 'loading'} +{#if $query.status === 'pending'}

    Loading...

    {/if} diff --git a/examples/svelte/star-wars/src/routes/films/[filmId]/+page.svelte b/examples/svelte/star-wars/src/routes/films/[filmId]/+page.svelte index 988ccc6ad59..5342487a6ee 100644 --- a/examples/svelte/star-wars/src/routes/films/[filmId]/+page.svelte +++ b/examples/svelte/star-wars/src/routes/films/[filmId]/+page.svelte @@ -18,7 +18,7 @@ }) -{#if $query.status === 'loading'} +{#if $query.status === 'pending'}

    Loading...

    {/if} diff --git a/packages/query-core/src/queryClient.ts b/packages/query-core/src/queryClient.ts index 6b43c6bc639..e3f004e3907 100644 --- a/packages/query-core/src/queryClient.ts +++ b/packages/query-core/src/queryClient.ts @@ -103,7 +103,7 @@ export class QueryClient { } isMutating(filters?: MutationFilters): number { - return this.#mutationCache.findAll({ ...filters, status: 'loading' }).length + return this.#mutationCache.findAll({ ...filters, status: 'pending' }).length } getQueryData( diff --git a/packages/query-core/src/types.ts b/packages/query-core/src/types.ts index ddfe99e0eac..11d4300139c 100644 --- a/packages/query-core/src/types.ts +++ b/packages/query-core/src/types.ts @@ -247,7 +247,7 @@ export interface QueryObserverOptions< */ select?: (data: TQueryData) => TData /** - * If set to `true`, the query will suspend when `status === 'loading'` + * If set to `true`, the query will suspend when `status === 'pending'` * and throw errors when `status === 'error'`. * Defaults to `false`. */ diff --git a/packages/react-query/src/__tests__/useMutationState.test.tsx b/packages/react-query/src/__tests__/useMutationState.test.tsx index 0c4886beff5..ebc71ab4fab 100644 --- a/packages/react-query/src/__tests__/useMutationState.test.tsx +++ b/packages/react-query/src/__tests__/useMutationState.test.tsx @@ -237,7 +237,7 @@ describe('useMutationState', () => { function Variables() { variables.push( useMutationState({ - filters: { mutationKey, status: 'loading' }, + filters: { mutationKey, status: 'pending' }, select: (mutation) => mutation.state.variables, }), ) diff --git a/packages/react-query/src/useMutationState.ts b/packages/react-query/src/useMutationState.ts index 631feaef5b2..a5d53fa64d6 100644 --- a/packages/react-query/src/useMutationState.ts +++ b/packages/react-query/src/useMutationState.ts @@ -17,7 +17,7 @@ export function useIsMutating( ): number { const client = useQueryClient(queryClient) return useMutationState( - { filters: { ...filters, status: 'loading' } }, + { filters: { ...filters, status: 'pending' } }, client, ).length } From 02d23a00a712854abeafe6a5a1af1943f4079c0d Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Sat, 18 Feb 2023 13:02:27 +0100 Subject: [PATCH 59/60] test: mutations don't have `isLoading` anymore --- packages/vue-query/src/__tests__/useMutation.types.test.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/vue-query/src/__tests__/useMutation.types.test.tsx b/packages/vue-query/src/__tests__/useMutation.types.test.tsx index f2c4040f904..6436868c18f 100644 --- a/packages/vue-query/src/__tests__/useMutation.types.test.tsx +++ b/packages/vue-query/src/__tests__/useMutation.types.test.tsx @@ -82,7 +82,7 @@ describe('Discriminated union return type', () => { const result: Expect> = true return result } - if (mutation.isLoading) { + if (mutation.isPending) { const result: Expect> = true return result } From 7fc156e7061d7287d457803f11507ead04bd517c Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Sat, 18 Feb 2023 14:58:51 +0100 Subject: [PATCH 60/60] docs: new features for simplified optimistic updates --- docs/react/guides/migrating-to-v5.md | 32 +++++++++++++++++++ .../pages/index.tsx | 2 +- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/docs/react/guides/migrating-to-v5.md b/docs/react/guides/migrating-to-v5.md index 055607f30d7..281e431e6c8 100644 --- a/docs/react/guides/migrating-to-v5.md +++ b/docs/react/guides/migrating-to-v5.md @@ -323,6 +323,38 @@ To understand the reasoning behing this change checkout the [v5 roadmap discussi ## New Features 🚀 +### Simplified optimistic updates + +We have a new, simplified way to perform optimistic updates by leveraging the returned `variables` from `useMutation`: + +```tsx + const queryInfo = useTodos() + const addTodoMutation = useMutation({ + mutationFn: (newTodo: string) => axios.post('/api/data', { text: newTodo }), + onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), + }) + + if (queryInfo.data) { + return ( +
      + {queryInfo.data.items.map((todo) => ( +
    • {todo.text}
    • + ))} + {addTodoMutation.isPending && ( +
    • + {addTodoMutation.variables} +
    • + )} +
    + ) + } +``` + +Here, we are only changing how the UI looks when the mutation is running instead of writing data directly to the cache. This works best if we only have one place where we need to show the optimistic update. For more details, have a look at the [optimistic updates documentation](../guides/optimistic-updates.md). + ### Eternal list: scalable infinite query with new maxPages option Infinite queries are great when infinite scroll or pagination are needed. diff --git a/examples/react/optimistic-updates-typescript/pages/index.tsx b/examples/react/optimistic-updates-typescript/pages/index.tsx index b08fc7f4a99..c25694a53f6 100755 --- a/examples/react/optimistic-updates-typescript/pages/index.tsx +++ b/examples/react/optimistic-updates-typescript/pages/index.tsx @@ -74,7 +74,7 @@ function Example() { {queryInfo.data.items.map((todo) => (
  • {todo.text}
  • ))} - {addTodoMutation.isLoading && ( + {addTodoMutation.isPending && (