Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/giant-apples-wear.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/query-core': patch
---

Fix: onMutate callback now runs synchronously when mutationCache.config.onMutate is not defined
24 changes: 24 additions & 0 deletions packages/query-core/src/__tests__/mutationCache.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,30 @@ describe('mutationCache', () => {

expect(states).toEqual([1, 2, 3, 4])
})

test('options.onMutate should run synchronously when mutationCache.config.onMutate is not defined', () => {
const key = queryKey()
const states: Array<string> = []

// No onMutate in cache config
const testCache = new MutationCache({})
const testClient = new QueryClient({ mutationCache: testCache })

executeMutation(
testClient,
{
mutationKey: key,
mutationFn: () => sleep(10).then(() => ({ data: 5 })),
onMutate: () => {
states.push('onMutate')
return 'context'
},
},
'vars',
)

expect(states).toEqual(['onMutate'])
})
})

describe('find', () => {
Expand Down
12 changes: 7 additions & 5 deletions packages/query-core/src/mutation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,11 +212,13 @@ export class Mutation<
} else {
this.#dispatch({ type: 'pending', variables, isPaused })
// Notify cache callback
await this.#mutationCache.config.onMutate?.(
variables,
this as Mutation<unknown, unknown, unknown, unknown>,
mutationFnContext,
)
if (this.#mutationCache.config.onMutate) {
await this.#mutationCache.config.onMutate(
variables,
this as Mutation<unknown, unknown, unknown, unknown>,
mutationFnContext,
)
}
const context = await this.options.onMutate?.(
variables,
mutationFnContext,
Expand Down
Loading