From 2acab41994be1e81b8c3807ff4b572b8685a996d Mon Sep 17 00:00:00 2001 From: TkDodo Date: Sun, 22 Nov 2026 10:52:34 +0100 Subject: [PATCH 1/2] refactor(query-core)!: move mutation construction out of the cache --- .changeset/v6-mutation-construction.md | 5 + .../src/__tests__/inject-is-mutating.test.ts | 3 +- .../__tests__/inject-mutation-state.test.ts | 5 +- .../src/__tests__/useMutationState.test.ts | 4 +- .../src/__tests__/useMutationState.test.tsx | 21 ++-- .../src/__tests__/mutation.test-d.tsx | 28 +++--- .../src/__tests__/mutation.test.tsx | 41 ++++---- .../src/__tests__/mutationCache.test-d.tsx | 10 +- .../src/__tests__/mutationCache.test.tsx | 18 ++-- packages/query-core/src/__tests__/utils.ts | 6 +- packages/query-core/src/hydration.ts | 6 +- packages/query-core/src/mutation.ts | 25 +++++ packages/query-core/src/mutationCache.ts | 32 ++---- packages/query-core/src/mutationObserver.ts | 8 +- .../src/__tests__/Devtools.test.tsx | 99 ++++++++----------- .../src/__tests__/utils.test.ts | 10 +- .../src/__tests__/persist.test.ts | 3 +- .../src/__tests__/retryStrategies.test.ts | 4 +- .../src/__tests__/useMutationState.test.tsx | 21 ++-- .../src/__tests__/useIsMutating.test.tsx | 5 +- 20 files changed, 178 insertions(+), 176 deletions(-) create mode 100644 .changeset/v6-mutation-construction.md diff --git a/.changeset/v6-mutation-construction.md b/.changeset/v6-mutation-construction.md new file mode 100644 index 00000000000..8daa62884ca --- /dev/null +++ b/.changeset/v6-mutation-construction.md @@ -0,0 +1,5 @@ +--- +'@tanstack/query-core': major +--- + +Move mutation construction to `Mutation.build(client, options, state?)`. Replace calls to the internal `MutationCache.build` method with this static method. Query-only bundles can now omit mutation execution code. diff --git a/packages/angular-query/src/__tests__/inject-is-mutating.test.ts b/packages/angular-query/src/__tests__/inject-is-mutating.test.ts index 3188eb7af14..0cf5088ab34 100644 --- a/packages/angular-query/src/__tests__/inject-is-mutating.test.ts +++ b/packages/angular-query/src/__tests__/inject-is-mutating.test.ts @@ -1,5 +1,6 @@ import { Component, input, inputBinding, signal } from '@angular/core' import { TestBed } from '@angular/core/testing' +import { Mutation } from '@tanstack/query-core' import { createKey, sleep } from '@tanstack/query-test-utils' import { render } from '@testing-library/angular' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -89,7 +90,7 @@ describe('injectIsMutating', () => { }) it('should support signal reads in filter predicates', async () => { - const mutation = queryClient.getMutationCache().build(queryClient, { + const mutation = Mutation.build(queryClient, { mutationFn: () => sleep(100).then(() => 'data'), }) void mutation.execute(undefined) diff --git a/packages/angular-query/src/__tests__/inject-mutation-state.test.ts b/packages/angular-query/src/__tests__/inject-mutation-state.test.ts index 9b0d6d341c8..ba0cc75344c 100644 --- a/packages/angular-query/src/__tests__/inject-mutation-state.test.ts +++ b/packages/angular-query/src/__tests__/inject-mutation-state.test.ts @@ -6,6 +6,7 @@ import { signal, } from '@angular/core' import { TestBed } from '@angular/core/testing' +import { Mutation } from '@tanstack/query-core' import { sleep } from '@tanstack/query-test-utils' import { render } from '@testing-library/angular' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -37,8 +38,8 @@ describe('injectMutationState', () => { it('publishes selected mutation values unchanged and compares snapshot entries by identity', () => { const version = signal('before') - queryClient.getMutationCache().build(queryClient, { mutationKey: ['a'] }) - queryClient.getMutationCache().build(queryClient, { mutationKey: ['b'] }) + Mutation.build(queryClient, { mutationKey: ['a'] }) + Mutation.build(queryClient, { mutationKey: ['b'] }) let selected: Array<{ value: string }> = [] const states = TestBed.runInInjectionContext(() => injectMutationState(() => { diff --git a/packages/lit-query/src/__tests__/useMutationState.test.ts b/packages/lit-query/src/__tests__/useMutationState.test.ts index a91a5728604..f3e5005668a 100644 --- a/packages/lit-query/src/__tests__/useMutationState.test.ts +++ b/packages/lit-query/src/__tests__/useMutationState.test.ts @@ -1,4 +1,4 @@ -import { QueryClient } from '@tanstack/query-core' +import { Mutation, QueryClient } from '@tanstack/query-core' import { createKey, sleep } from '@tanstack/query-test-utils' import { LitElement, html } from 'lit' import { @@ -88,7 +88,7 @@ describe('useMutationState', () => { it('should not request another update when mutation cache emits with unchanged selected state', async () => { const mutationKey = createKey() - const existingMutation = queryClient.getMutationCache().build(queryClient, { + const existingMutation = Mutation.build(queryClient, { mutationKey, }) diff --git a/packages/preact-query/src/__tests__/useMutationState.test.tsx b/packages/preact-query/src/__tests__/useMutationState.test.tsx index 78e6f0acbd9..4a9805b5b25 100644 --- a/packages/preact-query/src/__tests__/useMutationState.test.tsx +++ b/packages/preact-query/src/__tests__/useMutationState.test.tsx @@ -1,10 +1,11 @@ +import { Mutation } from '@tanstack/query-core' import { createKey, sleep } from '@tanstack/query-test-utils' import { fireEvent, render } from '@testing-library/preact' import { useEffect } from 'preact/hooks' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { QueryClient, useIsMutating, useMutation, useMutationState } from '..' import { renderWithClient } from './utils' -import type { Mutation, MutationCacheNotifyEvent } from '..' +import type { MutationCacheNotifyEvent } from '..' describe('useIsMutating', () => { beforeEach(() => { @@ -214,7 +215,7 @@ describe('useIsMutating', () => { const queryClient = new QueryClient() const key = createKey() const otherKey = createKey() - const mutation = queryClient.getMutationCache().build(queryClient, { + const mutation = Mutation.build(queryClient, { mutationKey: key, mutationFn: () => sleep(100), }) @@ -251,8 +252,8 @@ describe('useMutationState', () => { const key1 = createKey() const key2 = createKey() const cache = queryClient.getMutationCache() - cache.build(queryClient, { mutationKey: key1 }) - cache.build(queryClient, { mutationKey: key2 }) + Mutation.build(queryClient, { mutationKey: key1 }) + Mutation.build(queryClient, { mutationKey: key2 }) const onCacheChange = vi.fn<(event: MutationCacheNotifyEvent) => void>() const unsubscribe = cache.subscribe(onCacheChange) @@ -283,7 +284,7 @@ describe('useMutationState', () => { it('should update when select changes without a cache update', () => { const queryClient = new QueryClient() const key = createKey() - queryClient.getMutationCache().build(queryClient, { mutationKey: key }) + Mutation.build(queryClient, { mutationKey: key }) function Page({ select }: { select: (mutation: Mutation) => unknown }) { const result = useMutationState({ select }) @@ -308,7 +309,7 @@ describe('useMutationState', () => { const queryClient = new QueryClient() const key = createKey() const cache = queryClient.getMutationCache() - const existingMutation = cache.build(queryClient, { + const existingMutation = Mutation.build(queryClient, { mutationKey: key, meta: { time: 0 }, }) @@ -357,7 +358,7 @@ describe('useMutationState', () => { it('should render selector results that cannot be structurally shared', () => { const queryClient = new QueryClient() const key = createKey() - queryClient.getMutationCache().build(queryClient, { mutationKey: key }) + Mutation.build(queryClient, { mutationKey: key }) function Page({ time }: { time: number }) { const result = useMutationState({ @@ -456,7 +457,7 @@ describe('useMutationState', () => { (inputs) => { const queryClient = new QueryClient() const key = createKey() - queryClient.getMutationCache().build(queryClient, { mutationKey: key }) + Mutation.build(queryClient, { mutationKey: key }) const onResult = vi.fn< (result: Array<{ key: ReadonlyArray | undefined }>) => void @@ -493,8 +494,8 @@ describe('useMutationState', () => { const client2 = new QueryClient() const key1 = createKey() const key2 = createKey() - client1.getMutationCache().build(client1, { mutationKey: key1 }) - client2.getMutationCache().build(client2, { mutationKey: key2 }) + Mutation.build(client1, { mutationKey: key1 }) + Mutation.build(client2, { mutationKey: key2 }) const select = (mutation: Mutation) => mutation.options.mutationKey function Page({ client }: { client: QueryClient }) { diff --git a/packages/query-core/src/__tests__/mutation.test-d.tsx b/packages/query-core/src/__tests__/mutation.test-d.tsx index 765ef250296..e2e692e6269 100644 --- a/packages/query-core/src/__tests__/mutation.test-d.tsx +++ b/packages/query-core/src/__tests__/mutation.test-d.tsx @@ -1,7 +1,7 @@ import { describe, expectTypeOf, it } from 'vitest' -import { MutationCache } from '../mutationCache' +import { Mutation } from '../mutation' import { QueryClient } from '../queryClient' -import type { Action, Mutation, MutationState } from '../mutation' +import type { Action, MutationState } from '../mutation' import type { MutationObserver } from '../mutationObserver' import type { DefaultError, @@ -193,7 +193,7 @@ describe('mutation', () => { describe('state', () => { it('should be the mutation state for the same type parameters', () => { - const mutation = new MutationCache().build< + const mutation = Mutation.build< { value: string }, CustomError, number, @@ -224,7 +224,7 @@ describe('mutation', () => { describe('options', () => { it('should be the mutation options for the same type parameters', () => { - const mutation = new MutationCache().build< + const mutation = Mutation.build< { value: string }, CustomError, number, @@ -262,7 +262,7 @@ describe('mutation', () => { describe('setOptions', () => { it('should take the mutation options and return nothing', () => { - const mutation = new MutationCache().build< + const mutation = Mutation.build< { value: string }, CustomError, number, @@ -286,7 +286,7 @@ describe('mutation', () => { describe('meta', () => { it('should be the mutation meta or undefined', () => { - const mutation = new MutationCache().build< + const mutation = Mutation.build< { value: string }, CustomError, number, @@ -300,7 +300,7 @@ describe('mutation', () => { }) it('should be a getter without a setter', () => { - const mutation = new MutationCache().build< + const mutation = Mutation.build< { value: string }, CustomError, number, @@ -321,7 +321,7 @@ describe('mutation', () => { describe('addObserver', () => { it('should take a single observer and return nothing', () => { - const mutation = new MutationCache().build< + const mutation = Mutation.build< { value: string }, CustomError, number, @@ -340,7 +340,7 @@ describe('mutation', () => { describe('removeObserver', () => { it('should take a single observer and return nothing', () => { - const mutation = new MutationCache().build< + const mutation = Mutation.build< { value: string }, CustomError, number, @@ -359,7 +359,7 @@ describe('mutation', () => { describe('continue', () => { it('should take no arguments and resolve with an unknown value', () => { - const mutation = new MutationCache().build< + const mutation = Mutation.build< { value: string }, CustomError, number, @@ -376,7 +376,7 @@ describe('mutation', () => { describe('execute', () => { it('should take the variables and resolve with the data', () => { - const mutation = new MutationCache().build< + const mutation = Mutation.build< { value: string }, CustomError, number, @@ -393,7 +393,7 @@ describe('mutation', () => { }) it('should reject variables of another type', () => { - const mutation = new MutationCache().build< + const mutation = Mutation.build< { value: string }, CustomError, number, @@ -412,7 +412,7 @@ describe('mutation', () => { describe('gcTime', () => { it('should be a number inherited from Removable', () => { - const mutation = new MutationCache().build< + const mutation = Mutation.build< { value: string }, CustomError, number, @@ -428,7 +428,7 @@ describe('mutation', () => { describe('destroy', () => { it('should take no arguments and return nothing', () => { - const mutation = new MutationCache().build< + const mutation = Mutation.build< { value: string }, CustomError, number, diff --git a/packages/query-core/src/__tests__/mutation.test.tsx b/packages/query-core/src/__tests__/mutation.test.tsx index b9f8088424f..fd98e764e32 100644 --- a/packages/query-core/src/__tests__/mutation.test.tsx +++ b/packages/query-core/src/__tests__/mutation.test.tsx @@ -1,6 +1,7 @@ import { createKey, sleep } from '@tanstack/query-test-utils' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { MutationCache, QueryClient, focusManager, onlineManager } from '..' +import { Mutation } from '../mutation' import { MutationObserver } from '../mutationObserver' import { executeMutation, mockOnlineManagerIsOnline } from './utils' import type { MutationCacheNotifyEvent, MutationFunctionContext } from '..' @@ -274,25 +275,23 @@ describe('mutation', () => { onSettled, }) - const mutation = queryClient - .getMutationCache() - .build( - queryClient, - { - mutationKey: key, - }, - { - context: 'todo', - data: undefined, - error: null, - failureCount: 1, - failureReason: 'err', - isPaused: true, - status: 'pending', - variables: 'todo', - submittedAt: 1, - }, - ) + const mutation = Mutation.build( + queryClient, + { + mutationKey: key, + }, + { + context: 'todo', + data: undefined, + error: null, + failureCount: 1, + failureReason: 'err', + isPaused: true, + status: 'pending', + variables: 'todo', + submittedAt: 1, + }, + ) expect(mutation.state).toStrictEqual({ context: 'todo', @@ -349,7 +348,7 @@ describe('mutation', () => { it('should not add an existing observer with addObserver', () => { const mutationCache = queryClient.getMutationCache() const observer = new MutationObserver(queryClient, {}) - const currentMutation = mutationCache.build(queryClient, {}) + const currentMutation = Mutation.build(queryClient, {}) const fn = vi.fn<(type: MutationCacheNotifyEvent['type']) => void>() @@ -1595,7 +1594,7 @@ describe('mutation', () => { sleep(10).then(() => 'data'), ) // a mutation restored from a dehydrated pending state has no retryer yet - const mutation = queryClient.getMutationCache().build( + const mutation = Mutation.build( queryClient, { mutationFn }, { diff --git a/packages/query-core/src/__tests__/mutationCache.test-d.tsx b/packages/query-core/src/__tests__/mutationCache.test-d.tsx index e0f96b548ce..deb68300b5c 100644 --- a/packages/query-core/src/__tests__/mutationCache.test-d.tsx +++ b/packages/query-core/src/__tests__/mutationCache.test-d.tsx @@ -1,8 +1,8 @@ import { afterEach, beforeEach, describe, expectTypeOf, it } from 'vitest' import { MutationCache, QueryClient } from '..' +import { Mutation } from '../mutation' import type { DefaultError, - Mutation, MutationCacheConfig, MutationCacheNotifyEvent, MutationFilters, @@ -35,7 +35,7 @@ describe('mutationCache', () => { | 'subscribe' | 'hasListeners' | 'config' - | 'build' + | 'register' | 'add' | 'remove' | 'canRun' @@ -266,9 +266,9 @@ describe('mutationCache', () => { }) }) - describe('build', () => { + describe('Mutation.build', () => { it('should carry its type parameters into the mutation it returns', () => { - const mutation = mutationCache.build< + const mutation = Mutation.build< { value: string }, CustomError, number, @@ -290,7 +290,7 @@ describe('mutationCache', () => { it('should accept an optional initial state', () => { expectTypeOf( - mutationCache.build<{ value: string }, CustomError, number, string>, + Mutation.build<{ value: string }, CustomError, number, string>, ) .parameter(2) .toEqualTypeOf< diff --git a/packages/query-core/src/__tests__/mutationCache.test.tsx b/packages/query-core/src/__tests__/mutationCache.test.tsx index 13d17265847..103f2f08e1e 100644 --- a/packages/query-core/src/__tests__/mutationCache.test.tsx +++ b/packages/query-core/src/__tests__/mutationCache.test.tsx @@ -1,10 +1,10 @@ import { createKey, sleep } from '@tanstack/query-test-utils' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { MutationCache, MutationObserver, QueryClient } from '..' +import { Mutation } from '../mutation' import { executeMutation } from './utils' import type { DefaultError, - Mutation, MutationCacheNotifyEvent, MutationFunctionContext, } from '..' @@ -528,8 +528,8 @@ describe('mutationCache', () => { it('should notify subscribers after all mutations have been removed', () => { const testCache = new MutationCache() const testClient = new QueryClient({ mutationCache: testCache }) - const mutation1 = testCache.build(testClient, {}) - const mutation2 = testCache.build(testClient, {}) + const mutation1 = Mutation.build(testClient, {}) + const mutation2 = Mutation.build(testClient, {}) const callback = vi.fn< () => Array> >(() => testCache.getAll()) @@ -554,11 +554,11 @@ describe('mutationCache', () => { it('should preserve mutations added by removal subscribers', () => { const testCache = new MutationCache() const testClient = new QueryClient({ mutationCache: testCache }) - const original = testCache.build(testClient, {}) + const original = Mutation.build(testClient, {}) const key = createKey() testCache.subscribe((event) => { if (event.type === 'removed' && event.mutation === original) { - testCache.build(testClient, { mutationKey: key }) + Mutation.build(testClient, { mutationKey: key }) } }) @@ -574,11 +574,11 @@ describe('mutationCache', () => { const testCache = new MutationCache() const testClient = new QueryClient({ mutationCache: testCache }) - const mutation1 = testCache.build(testClient, { + const mutation1 = Mutation.build(testClient, { scope: { id: 'scope1' }, mutationFn: () => Promise.resolve('data1'), }) - const mutation2 = testCache.build(testClient, { + const mutation2 = Mutation.build(testClient, { scope: { id: 'scope1' }, mutationFn: () => Promise.resolve('data2'), }) @@ -595,7 +595,7 @@ describe('mutationCache', () => { const testCache = new MutationCache() const testClient = new QueryClient({ mutationCache: testCache }) - const mutation = testCache.build(testClient, { + const mutation = Mutation.build(testClient, { scope: { id: 'scope1' }, mutationFn: () => Promise.resolve('data'), }) @@ -611,7 +611,7 @@ describe('mutationCache', () => { const testCache = new MutationCache() const testClient = new QueryClient({ mutationCache: testCache }) - const mutation = testCache.build(testClient, { + const mutation = Mutation.build(testClient, { mutationFn: () => Promise.resolve('data'), }) diff --git a/packages/query-core/src/__tests__/utils.ts b/packages/query-core/src/__tests__/utils.ts index 0ef734bc8fb..294cd139e3e 100644 --- a/packages/query-core/src/__tests__/utils.ts +++ b/packages/query-core/src/__tests__/utils.ts @@ -1,5 +1,6 @@ import { vi } from 'vitest' import { environmentManager, onlineManager } from '..' +import { Mutation } from '../mutation' import type { MockInstance } from 'vitest' import type { MutationOptions, QueryClient } from '..' @@ -14,10 +15,7 @@ export function executeMutation( options: MutationOptions, variables: TVariables, ) { - return queryClient - .getMutationCache() - .build(queryClient, options) - .execute(variables) + return Mutation.build(queryClient, options).execute(variables) } export function setIsServer(value: boolean) { diff --git a/packages/query-core/src/hydration.ts b/packages/query-core/src/hydration.ts index d35c743d928..49b24a8ed1b 100644 --- a/packages/query-core/src/hydration.ts +++ b/packages/query-core/src/hydration.ts @@ -1,5 +1,6 @@ +import { Mutation } from './mutation' import { noop } from './utils' -import type { Mutation, MutationState } from './mutation' +import type { MutationState } from './mutation' import type { Query, QueryState } from './query' import type { QueryClient } from './queryClient' import type { @@ -308,14 +309,13 @@ export function hydrate( dehydratedState: Partial, options?: HydrateOptions, ): void { - const mutationCache = client.getMutationCache() const queryCache = client.getQueryCache() const deserializeData = options?.defaultOptions?.deserializeData ?? client.getDefaultOptions().hydrate?.deserializeData dehydratedState.mutations?.forEach(({ state, ...mutationOptions }) => { - mutationCache.build( + Mutation.build( client, { ...client.getDefaultOptions().hydrate?.mutations, diff --git a/packages/query-core/src/mutation.ts b/packages/query-core/src/mutation.ts index 46edc7e2e4f..94d0422be58 100644 --- a/packages/query-core/src/mutation.ts +++ b/packages/query-core/src/mutation.ts @@ -152,6 +152,31 @@ export class Mutation< #mutationCache: MutationCache #retryer?: Retryer + /** + * Creates a mutation with the client's defaults and adds it to the cache. + * @param client - Supplies defaults and the mutation cache. + * @param options - The options for the new mutation. + * @param state - The initial state, for example when hydrating a paused mutation. + * @returns The registered mutation. + */ + static build( + client: QueryClient, + options: MutationOptions, + state?: MutationState, + ): Mutation { + const cache = client.getMutationCache() + return cache.register( + (mutationId) => + new Mutation({ + client, + mutationCache: cache, + mutationId, + options: client.defaultMutationOptions(options), + state, + }), + ) + } + constructor( config: MutationConfig, ) { diff --git a/packages/query-core/src/mutationCache.ts b/packages/query-core/src/mutationCache.ts index 31a539926fa..f7d3463c7f2 100644 --- a/packages/query-core/src/mutationCache.ts +++ b/packages/query-core/src/mutationCache.ts @@ -1,14 +1,11 @@ -import { Mutation } from './mutation' import { notifyManager } from './notifyManager' import { Subscribable } from './subscribable' import { matchMutation, noop } from './utils' -import type { Action, MutationState } from './mutation' +import type { Action, Mutation } from './mutation' import type { MutationObserver } from './mutationObserver' -import type { QueryClient } from './queryClient' import type { DefaultError, MutationFunctionContext, - MutationOptions, NotifyEvent, } from './types' import type { MutationFilters } from './utils' @@ -133,29 +130,16 @@ export class MutationCache extends Subscribable { } /** - * Creates a mutation and adds it to the cache. + * Assigns the next cache-local ID and registers the mutation. + * @param create - Constructs the mutation with the assigned ID. + * @returns The mutation added to this cache. * @internal - * @param client - The client the mutation belongs to, used to default its options. - * @param options - The mutation options. They are defaulted with {@link - * QueryClient#defaultMutationOptions}. - * @param state - The initial state of the mutation, e.g. when restoring a dehydrated mutation. - * @returns The new mutation, already added to the cache. */ - build( - client: QueryClient, - options: MutationOptions, - state?: MutationState, - ): Mutation { - const mutation = new Mutation({ - client, - mutationCache: this, - mutationId: ++this.#mutationId, - options: client.defaultMutationOptions(options), - state, - }) - + register>( + create: (id: number) => T, + ): T { + const mutation = create(++this.#mutationId) this.add(mutation) - return mutation } diff --git a/packages/query-core/src/mutationObserver.ts b/packages/query-core/src/mutationObserver.ts index e52a3fd335a..2508d09e316 100644 --- a/packages/query-core/src/mutationObserver.ts +++ b/packages/query-core/src/mutationObserver.ts @@ -1,8 +1,8 @@ -import { getDefaultState } from './mutation' +import { Mutation, getDefaultState } from './mutation' import { notifyManager } from './notifyManager' import { Subscribable } from './subscribable' import { hashKey, shallowEqualObjects } from './utils' -import type { Action, Mutation } from './mutation' +import type { Action } from './mutation' import type { QueryClient } from './queryClient' import type { DefaultError, @@ -222,9 +222,7 @@ export class MutationObserver< this.#currentMutation?.removeObserver(this) - this.#currentMutation = this.#client - .getMutationCache() - .build(this.#client, this.options) + this.#currentMutation = Mutation.build(this.#client, this.options) this.#currentMutation.addObserver(this) diff --git a/packages/query-devtools/src/__tests__/Devtools.test.tsx b/packages/query-devtools/src/__tests__/Devtools.test.tsx index c9880b63cd5..d9f2cc85f04 100644 --- a/packages/query-devtools/src/__tests__/Devtools.test.tsx +++ b/packages/query-devtools/src/__tests__/Devtools.test.tsx @@ -1,6 +1,7 @@ import { createLocalStorage } from '@solid-primitives/storage' import { cleanup, fireEvent, render, within } from '@solidjs/testing-library' import { + Mutation, QueryClient, QueryObserver, dehydrate, @@ -249,7 +250,7 @@ describe('Devtools', () => { it('keeps mutation clicks aligned after a same-count sort change', () => { for (let index = 0; index < 100; index++) { - queryClient.getMutationCache().build(queryClient, { + Mutation.build(queryClient, { mutationKey: [`reorder-${index}`], }) } @@ -270,7 +271,7 @@ describe('Devtools', () => { it('bounds mutation rows, preserves offscreen details, and filters from a distant offset', async () => { const mutations = Array.from({ length: 2000 }, (_, index) => - queryClient.getMutationCache().build(queryClient, { + Mutation.build(queryClient, { mutationKey: [ index === 1999 ? 'mutation-target' : `mutation-${index}`, ], @@ -406,18 +407,14 @@ describe('Devtools', () => { it('should keep mutation selection, notifications, and cleanup independent', async () => { const secondClient = new QueryClient() - const firstMutation = queryClient - .getMutationCache() - .build(queryClient, { - mutationKey: ['mutation-a'], - mutationFn: () => Promise.resolve('first-result'), - }) - const secondMutation = secondClient - .getMutationCache() - .build(secondClient, { - mutationKey: ['mutation-b'], - mutationFn: () => Promise.resolve('second-result'), - }) + const firstMutation = Mutation.build(queryClient, { + mutationKey: ['mutation-a'], + mutationFn: () => Promise.resolve('first-result'), + }) + const secondMutation = Mutation.build(secondClient, { + mutationKey: ['mutation-b'], + mutationFn: () => Promise.resolve('second-result'), + }) const firstRender = mount() const secondRender = mount(secondClient) const first = within(firstRender.container) @@ -535,13 +532,10 @@ describe('Devtools', () => { fireEvent.click(panel.getByText('Mutations')) setClient(secondClient) - await secondClient - .getMutationCache() - .build(secondClient, { - mutationKey: ['switch-mutation'], - mutationFn: () => Promise.resolve('new-result'), - }) - .execute({}) + await Mutation.build(secondClient, { + mutationKey: ['switch-mutation'], + mutationFn: () => Promise.resolve('new-result'), + }).execute({}) await vi.advanceTimersByTimeAsync(0) expect(panel.getAllByLabelText(/Mutation submitted at/)).toHaveLength(1) rendered.unmount() @@ -565,13 +559,10 @@ describe('Devtools', () => { const panel = within(rendered.container) fireEvent.click(panel.getByText('Mutations')) - void queryClient - .getMutationCache() - .build(queryClient, { - mutationKey: ['previous-mutation'], - mutationFn: () => new Promise(noop), - }) - .execute({}) + void Mutation.build(queryClient, { + mutationKey: ['previous-mutation'], + mutationFn: () => new Promise(noop), + }).execute({}) setClient(secondClient) await vi.advanceTimersByTimeAsync(0) @@ -964,7 +955,7 @@ describe('Devtools', () => { fireEvent.click(rendered.getByText('Mutations')) - const mutation = queryClient.getMutationCache().build(queryClient, { + const mutation = Mutation.build(queryClient, { mutationKey: ['add-post'], mutationFn: () => Promise.resolve('ok'), }) @@ -980,7 +971,7 @@ describe('Devtools', () => { fireEvent.click(rendered.getByText('Mutations')) - queryClient.getMutationCache().build(queryClient, { + Mutation.build(queryClient, { mutationKey: ['idle-mut'], mutationFn: () => Promise.resolve('ok'), }) @@ -1303,12 +1294,12 @@ describe('Devtools', () => { }) it('searches read-only mutation Data and resets search when the selection changes', async () => { - const first = queryClient.getMutationCache().build(queryClient, { + const first = Mutation.build(queryClient, { mutationKey: ['search-first'], mutationFn: () => Promise.resolve({ nested: { name: 'mutation needle' } }), }) - const second = queryClient.getMutationCache().build(queryClient, { + const second = Mutation.build(queryClient, { mutationKey: ['search-second'], mutationFn: () => Promise.resolve({ nested: { name: 'other' } }), }) @@ -1377,20 +1368,17 @@ describe('Devtools', () => { 'should initialize matching mutation explorers from the %s scope', async (scope) => { for (const source of ['data', 'variables', 'both']) { - await queryClient - .getMutationCache() - .build(queryClient, { - mutationKey: ['needle', source], - mutationFn: () => - Promise.resolve({ - nested: { - name: source === 'variables' ? 'other' : 'data needle', - }, - }), - }) - .execute({ - nested: { name: source === 'data' ? 'other' : 'variable needle' }, - }) + await Mutation.build(queryClient, { + mutationKey: ['needle', source], + mutationFn: () => + Promise.resolve({ + nested: { + name: source === 'variables' ? 'other' : 'data needle', + }, + }), + }).execute({ + nested: { name: source === 'data' ? 'other' : 'variable needle' }, + }) } const rendered = renderDevtools( { initialIsOpen: true }, @@ -1566,7 +1554,7 @@ describe('Devtools', () => { fireEvent.click(rendered.getByText('Mutations')) - const mutation = queryClient.getMutationCache().build(queryClient, { + const mutation = Mutation.build(queryClient, { mutationKey: ['mutation-detail'], mutationFn: () => Promise.resolve('ok'), }) @@ -1603,7 +1591,7 @@ describe('Devtools', () => { async (scope) => { let resolve!: () => void const variables = { name: 'before' } - const mutation = queryClient.getMutationCache().build(queryClient, { + const mutation = Mutation.build(queryClient, { mutationKey: ['update-variables'], mutationFn: async (input: typeof variables) => { await new Promise((done) => { @@ -1658,11 +1646,11 @@ describe('Devtools', () => { const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click(rendered.getByText('Mutations')) - const matching = queryClient.getMutationCache().build(queryClient, { + const matching = Mutation.build(queryClient, { mutationKey: ['filter-match'], mutationFn: () => Promise.resolve('ok'), }) - const other = queryClient.getMutationCache().build(queryClient, { + const other = Mutation.build(queryClient, { mutationKey: ['filter-other'], mutationFn: () => Promise.resolve('ok'), }) @@ -1689,13 +1677,10 @@ describe('Devtools', () => { ) fireEvent.click(rendered.getByText('Mutations')) const execute = (key: string, variables: unknown, data: unknown) => - queryClient - .getMutationCache() - .build(queryClient, { - mutationKey: [key], - mutationFn: () => Promise.resolve(data), - }) - .execute(variables) + Mutation.build(queryClient, { + mutationKey: [key], + mutationFn: () => Promise.resolve(data), + }).execute(variables) execute('by-variables', { title: 'Needle' }, 'ok') execute('by-data', { title: 'other' }, { id: 'needle-1' }) execute('needle-key', { title: 'other' }, 'ok') diff --git a/packages/query-devtools/src/__tests__/utils.test.ts b/packages/query-devtools/src/__tests__/utils.test.ts index 7918d79c01d..38de171bd3e 100644 --- a/packages/query-devtools/src/__tests__/utils.test.ts +++ b/packages/query-devtools/src/__tests__/utils.test.ts @@ -1,5 +1,5 @@ import { runInNewContext } from 'node:vm' -import { QueryClient, QueryObserver } from '@tanstack/query-core' +import { Mutation, QueryClient, QueryObserver } from '@tanstack/query-core' import { createRoot } from 'solid-js' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { @@ -1198,9 +1198,11 @@ describe('Utils tests', () => { } function buildMutation(overrides: Partial): Mutation { - return queryClient - .getMutationCache() - .build(queryClient, {}, { ...defaultMutationState, ...overrides }) + return Mutation.build( + queryClient, + {}, + { ...defaultMutationState, ...overrides }, + ) } beforeEach(() => { 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 4fc1ba3ee2d..c71891075d2 100644 --- a/packages/query-persist-client-core/src/__tests__/persist.test.ts +++ b/packages/query-persist-client-core/src/__tests__/persist.test.ts @@ -1,4 +1,5 @@ import { + Mutation, MutationObserver, QueriesObserver, QueryClient, @@ -33,7 +34,7 @@ describe('persist', () => { dehydrateOptions: { shouldDehydrateMutation: () => true }, }) - queryClient.getMutationCache().build(queryClient, { + Mutation.build(queryClient, { mutationFn: (text: string) => Promise.resolve(text), }) diff --git a/packages/query-persist-client-core/src/__tests__/retryStrategies.test.ts b/packages/query-persist-client-core/src/__tests__/retryStrategies.test.ts index 94e0bd8abb4..d3fefa3a336 100644 --- a/packages/query-persist-client-core/src/__tests__/retryStrategies.test.ts +++ b/packages/query-persist-client-core/src/__tests__/retryStrategies.test.ts @@ -1,4 +1,4 @@ -import { QueryClient, dehydrate } from '@tanstack/query-core' +import { Mutation, QueryClient, dehydrate } from '@tanstack/query-core' import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { removeOldestQuery } from '../retryStrategies' import type { PersistedClient } from '../persist' @@ -83,7 +83,7 @@ describe('removeOldestQuery', () => { }) it('should preserve mutations when removing the oldest query', () => { - queryClient.getMutationCache().build(queryClient, { + Mutation.build(queryClient, { mutationFn: () => Promise.resolve('data'), }) const { mutations } = dehydrate(queryClient, { diff --git a/packages/react-query/src/__tests__/useMutationState.test.tsx b/packages/react-query/src/__tests__/useMutationState.test.tsx index ce7d44ea74a..a22294f5e80 100644 --- a/packages/react-query/src/__tests__/useMutationState.test.tsx +++ b/packages/react-query/src/__tests__/useMutationState.test.tsx @@ -1,10 +1,11 @@ +import { Mutation } from '@tanstack/query-core' import { createKey, sleep } from '@tanstack/query-test-utils' import { fireEvent, render } from '@testing-library/react' import * as React from 'react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { QueryClient, useIsMutating, useMutation, useMutationState } from '..' import { renderWithClient } from './utils' -import type { Mutation, MutationCacheNotifyEvent } from '..' +import type { MutationCacheNotifyEvent } from '..' describe('useIsMutating', () => { beforeEach(() => { @@ -214,7 +215,7 @@ describe('useIsMutating', () => { const queryClient = new QueryClient() const key = createKey() const otherKey = createKey() - const mutation = queryClient.getMutationCache().build(queryClient, { + const mutation = Mutation.build(queryClient, { mutationKey: key, mutationFn: () => sleep(100), }) @@ -251,8 +252,8 @@ describe('useMutationState', () => { const key1 = createKey() const key2 = createKey() const cache = queryClient.getMutationCache() - cache.build(queryClient, { mutationKey: key1 }) - cache.build(queryClient, { mutationKey: key2 }) + Mutation.build(queryClient, { mutationKey: key1 }) + Mutation.build(queryClient, { mutationKey: key2 }) const onCacheChange = vi.fn<(event: MutationCacheNotifyEvent) => void>() const unsubscribe = cache.subscribe(onCacheChange) @@ -283,7 +284,7 @@ describe('useMutationState', () => { it('should update when select changes without a cache update', () => { const queryClient = new QueryClient() const key = createKey() - queryClient.getMutationCache().build(queryClient, { mutationKey: key }) + Mutation.build(queryClient, { mutationKey: key }) function Page({ select }: { select: (mutation: Mutation) => unknown }) { const result = useMutationState({ select }) @@ -308,7 +309,7 @@ describe('useMutationState', () => { const queryClient = new QueryClient() const key = createKey() const cache = queryClient.getMutationCache() - const existingMutation = cache.build(queryClient, { + const existingMutation = Mutation.build(queryClient, { mutationKey: key, meta: { time: 0 }, }) @@ -357,7 +358,7 @@ describe('useMutationState', () => { it('should render selector results that cannot be structurally shared', () => { const queryClient = new QueryClient() const key = createKey() - queryClient.getMutationCache().build(queryClient, { mutationKey: key }) + Mutation.build(queryClient, { mutationKey: key }) function Page({ time }: { time: number }) { const result = useMutationState({ @@ -456,7 +457,7 @@ describe('useMutationState', () => { (inputs) => { const queryClient = new QueryClient() const key = createKey() - queryClient.getMutationCache().build(queryClient, { mutationKey: key }) + Mutation.build(queryClient, { mutationKey: key }) const onResult = vi.fn< (result: Array<{ key: ReadonlyArray | undefined }>) => void @@ -493,8 +494,8 @@ describe('useMutationState', () => { const client2 = new QueryClient() const key1 = createKey() const key2 = createKey() - client1.getMutationCache().build(client1, { mutationKey: key1 }) - client2.getMutationCache().build(client2, { mutationKey: key2 }) + Mutation.build(client1, { mutationKey: key1 }) + Mutation.build(client2, { mutationKey: key2 }) const select = (mutation: Mutation) => mutation.options.mutationKey function Page({ client }: { client: QueryClient }) { diff --git a/packages/solid-query/src/__tests__/useIsMutating.test.tsx b/packages/solid-query/src/__tests__/useIsMutating.test.tsx index dbaff8f9329..db0d83e433e 100644 --- a/packages/solid-query/src/__tests__/useIsMutating.test.tsx +++ b/packages/solid-query/src/__tests__/useIsMutating.test.tsx @@ -1,4 +1,5 @@ import { fireEvent, render } from '@solidjs/testing-library' +import { Mutation } from '@tanstack/query-core' import * as QueryCore from '@tanstack/query-core' import { createKey, sleep } from '@tanstack/query-test-utils' import { Show, createEffect, createRenderEffect, createSignal } from 'solid-js' @@ -213,7 +214,7 @@ describe('useIsMutating', () => { const rendered = render(() => ) - const firstMutation = queryClient1.getMutationCache().build(queryClient1, { + const firstMutation = Mutation.build(queryClient1, { mutationFn: () => sleep(20).then(() => 'data1'), }) const firstMutationPromise = firstMutation.execute(undefined) @@ -224,7 +225,7 @@ describe('useIsMutating', () => { expect(unsubscribe1).toHaveBeenCalledTimes(1) expect(rendered.getByText('mutating: 0')).toBeInTheDocument() - const secondMutation = queryClient2.getMutationCache().build(queryClient2, { + const secondMutation = Mutation.build(queryClient2, { mutationFn: () => sleep(20).then(() => 'data2'), }) const secondMutationPromise = secondMutation.execute(undefined) From 15a9150c9d713d6f09bc93a183f7af618aa5f690 Mon Sep 17 00:00:00 2001 From: TkDodo Date: Sun, 22 Nov 2026 11:45:58 +0100 Subject: [PATCH 2/2] test: fix mutation PR check failures --- packages/query-core/src/mutationCache.ts | 2 +- packages/query-devtools/src/__tests__/Devtools.test.tsx | 6 +++--- packages/query-devtools/src/__tests__/utils.test.ts | 1 - 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/packages/query-core/src/mutationCache.ts b/packages/query-core/src/mutationCache.ts index f7d3463c7f2..623169e1926 100644 --- a/packages/query-core/src/mutationCache.ts +++ b/packages/query-core/src/mutationCache.ts @@ -131,9 +131,9 @@ export class MutationCache extends Subscribable { /** * Assigns the next cache-local ID and registers the mutation. + * @internal * @param create - Constructs the mutation with the assigned ID. * @returns The mutation added to this cache. - * @internal */ register>( create: (id: number) => T, diff --git a/packages/query-devtools/src/__tests__/Devtools.test.tsx b/packages/query-devtools/src/__tests__/Devtools.test.tsx index d9f2cc85f04..9e2577a2573 100644 --- a/packages/query-devtools/src/__tests__/Devtools.test.tsx +++ b/packages/query-devtools/src/__tests__/Devtools.test.tsx @@ -176,8 +176,8 @@ describe('Devtools', () => { return viewport } - function seedQueries() { - for (let index = 0; index < 1000; index++) { + function seedQueries(count = 1000) { + for (let index = 0; index < count; index++) { queryClient.setQueryData( [`query-${String(index).padStart(4, '0')}`], `data-${index}`, @@ -207,7 +207,7 @@ describe('Devtools', () => { }) it('filters, clears, and restores queries after distant scrolling', () => { - seedQueries() + seedQueries(200) const rendered = renderDevtools({ initialIsOpen: true }) const viewport = getViewport(rendered.container, 'queries') viewport.scrollTo({ top: viewport.scrollHeight }) diff --git a/packages/query-devtools/src/__tests__/utils.test.ts b/packages/query-devtools/src/__tests__/utils.test.ts index 38de171bd3e..80e6c9767ec 100644 --- a/packages/query-devtools/src/__tests__/utils.test.ts +++ b/packages/query-devtools/src/__tests__/utils.test.ts @@ -18,7 +18,6 @@ import { } from '../utils' import type { FetchStatus, - Mutation, MutationStatus, Query, QueryKey,