Skip to content

Commit

Permalink
fix(core): do not update mutations if key has changed (#6889)
Browse files Browse the repository at this point in the history
* fix(core): do not update mutations if key has changed

* chore: remove .only test
  • Loading branch information
TkDodo committed Feb 13, 2024
1 parent 99559b6 commit 7e25569
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
3 changes: 2 additions & 1 deletion packages/query-core/src/mutationObserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,15 @@ export class MutationObserver<
observer: this,
})
}
this.#currentMutation?.setOptions(this.options)

if (
prevOptions?.mutationKey &&
this.options.mutationKey &&
hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey)
) {
this.reset()
} else {
this.#currentMutation?.setOptions(this.options)
}
}

Expand Down
43 changes: 43 additions & 0 deletions packages/query-core/src/tests/mutationObserver.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -126,4 +126,47 @@ describe('mutationObserver', () => {

unsubscribe()
})

test('changing mutation keys should not affect already existing mutations', async () => {
const key = queryKey()
const mutationObserver = new MutationObserver(queryClient, {
mutationKey: [...key, '1'],
mutationFn: async (text: string) => {
await sleep(5)
return text
},
})

const subscriptionHandler = vi.fn()

const unsubscribe = mutationObserver.subscribe(subscriptionHandler)

await mutationObserver.mutate('input')

expect(
queryClient.getMutationCache().find({ mutationKey: [...key, '1'] }),
).toMatchObject({
options: { mutationKey: [...key, '1'] },
state: {
status: 'success',
data: 'input',
},
})

mutationObserver.setOptions({
mutationKey: [...key, '2'],
})

expect(
queryClient.getMutationCache().find({ mutationKey: [...key, '1'] }),
).toMatchObject({
options: { mutationKey: [...key, '1'] },
state: {
status: 'success',
data: 'input',
},
})

unsubscribe()
})
})

0 comments on commit 7e25569

Please sign in to comment.