Skip to content

feat(query-core): add queryClient argument to mutation callbacks and mutationFn #9557

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

raymondanythings
Copy link

Background

When working with mutations, most callback logic (optimistic updates, cache updates, invalidations) needs direct access to queryClient.

Currently, this requires manually calling useQueryClient() inside callbacks, or wrapping mutation logic with custom hooks, which adds boilerplate.

PR #9193 proposes passing queryClient via MutationFunctionContext, but this changes callback parameter structures and may break compatibility with existing code.

What’s Different in This PR

Instead of replacing the last argument with a context object, this PR appends queryClient as the final parameter in:

  • mutationFn
  • onMutate
  • onSuccess
  • onError
  • onSettled

This preserves all existing parameters and their positions, making it fully backward-compatible for users who don’t use the new argument.

Example Usage

useMutation({
  mutationFn: (variables, queryClient) => {
    return api.updateItem(variables).then(res => {
      queryClient.invalidateQueries({ queryKey: ['items'] })
      return res
    })
  },
  onSuccess: (data, variables, _context, queryClient) => {
    queryClient.setQueryData(['items'], prev => [data, ...(prev ?? [])])
  }
})

Why This Approach

Backward-compatible: Does not alter existing argument order.

Low migration cost: Existing code works without changes.

Simple mental model: queryClient is always the last argument.

…te related callbacks

- Introduced a `client` parameter in the `MutationConfig` interface and updated the `Mutation` class to store it.
- Modified mutation function signatures to accept the `client` parameter, ensuring it is passed to success, error, and settled callbacks.
- Updated the `MutationCache` and `MutationObserver` classes to accommodate the new `client` parameter in their respective mutation handling logic.
…lbacks

- Added `queryClient` parameter to various mutation-related tests to ensure consistency with the updated mutation function signatures.
- Updated assertions in tests for `hydration`, `mutationObserver`, `mutations`, `utils`, and `useMutation` to reflect the inclusion of `queryClient` in callback invocations.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant