Skip to content

Commit 1e71dcb

Browse files
committed
fix(query-core): ensure onMutate runs synchronously when cache config is undefined
Fixes #8724
1 parent 060bd43 commit 1e71dcb

2 files changed

Lines changed: 31 additions & 5 deletions

File tree

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)