Skip to content

Commit e7258c5

Browse files
authored
fix(query-core): ensure onMutate runs synchronously when cache config is undefined (#8724) (#10066)
* chore: add changeset for onMutate sync fix * fix(query-core): ensure onMutate runs synchronously when cache config is undefined Fixes #8724
1 parent 7afff91 commit e7258c5

File tree

3 files changed

+36
-5
lines changed

3 files changed

+36
-5
lines changed

.changeset/giant-apples-wear.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@tanstack/query-core': patch
3+
---
4+
5+
Fix: onMutate callback now runs synchronously when mutationCache.config.onMutate is not defined

packages/query-core/src/__tests__/mutationCache.test.tsx

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,30 @@ describe('mutationCache', () => {
249249

250250
expect(states).toEqual([1, 2, 3, 4])
251251
})
252+
253+
test('options.onMutate should run synchronously when mutationCache.config.onMutate is not defined', () => {
254+
const key = queryKey()
255+
const states: Array<string> = []
256+
257+
// No onMutate in cache config
258+
const testCache = new MutationCache({})
259+
const testClient = new QueryClient({ mutationCache: testCache })
260+
261+
executeMutation(
262+
testClient,
263+
{
264+
mutationKey: key,
265+
mutationFn: () => sleep(10).then(() => ({ data: 5 })),
266+
onMutate: () => {
267+
states.push('onMutate')
268+
return 'context'
269+
},
270+
},
271+
'vars',
272+
)
273+
274+
expect(states).toEqual(['onMutate'])
275+
})
252276
})
253277

254278
describe('find', () => {

packages/query-core/src/mutation.ts

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -212,11 +212,13 @@ export class Mutation<
212212
} else {
213213
this.#dispatch({ type: 'pending', variables, isPaused })
214214
// Notify cache callback
215-
await this.#mutationCache.config.onMutate?.(
216-
variables,
217-
this as Mutation<unknown, unknown, unknown, unknown>,
218-
mutationFnContext,
219-
)
215+
if (this.#mutationCache.config.onMutate) {
216+
await this.#mutationCache.config.onMutate(
217+
variables,
218+
this as Mutation<unknown, unknown, unknown, unknown>,
219+
mutationFnContext,
220+
)
221+
}
220222
const context = await this.options.onMutate?.(
221223
variables,
222224
mutationFnContext,

0 commit comments

Comments
 (0)