Skip to content
Source
Sign inSign up
TanStack/query

feat(query-core): add MutationFunctionContext argument to mutateFn #9193

Closedtravikk(GitHub profile, opens in a new tab)wants to merge 4 commits intomain fromrefs/pull/9193/headopened View on GitHub

This PR adds new argument to mutateFn allowing for access to queryClient as well as meta object.

This feature should make it easier to attach authentication headers from within mutateFn, that would typically live in QueryCache. Currently that's made very difficult and requires either having singleton context in the codebase or requiring consumers of mutations to pass auth token each time.

This PR also makes it more similar to how queryFn behaves, in that it accepts QueryFunctionContext.

Note: I wasn't entirely sure about the name of MutateFunctionContext, but ultimately I decided to go ahead with that name to mirror the way queryFn behaves. I realise this might be suboptimal, due to there already existing a TContext for mutations. Happy to discuss and take direction here.

    1. github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: query-core

    2. TkDodocommented

      we already have a PR for this:

      can we consolidate the work in one PR?

      I think we’d want 3 properties passed:

      - mutationKey
      - meta
      - client
    3. @TkDodo updated as requested

    4. View your CI Pipeline Execution ↗ for commit 2c1a713843838739cce659e07da06d5748aee1cc.

      CommandStatusDurationResult
      nx affected --targets=test:sherif,test:knip,tes...❌ Failed2m 21sView ↗
      nx run-many --target=build --exclude=examples/*...✅ Succeeded1m 22sView ↗

      ☁️ Nx Cloud last updated this comment at 2025-06-19 08:32:16 UTC

    5. More templates

      @tanstack/angular-query-devtools-experimental

      npm i https://pkg.pr.new/@tanstack/angular-query-devtools-experimental@9193

      @tanstack/angular-query-experimental

      npm i https://pkg.pr.new/@tanstack/angular-query-experimental@9193

      @tanstack/eslint-plugin-query

      npm i https://pkg.pr.new/@tanstack/eslint-plugin-query@9193

      @tanstack/query-async-storage-persister

      npm i https://pkg.pr.new/@tanstack/query-async-storage-persister@9193

      @tanstack/query-broadcast-client-experimental

      npm i https://pkg.pr.new/@tanstack/query-broadcast-client-experimental@9193

      @tanstack/query-core

      npm i https://pkg.pr.new/@tanstack/query-core@9193

      @tanstack/query-devtools

      npm i https://pkg.pr.new/@tanstack/query-devtools@9193

      @tanstack/query-persist-client-core

      npm i https://pkg.pr.new/@tanstack/query-persist-client-core@9193

      @tanstack/query-sync-storage-persister

      npm i https://pkg.pr.new/@tanstack/query-sync-storage-persister@9193

      @tanstack/react-query

      npm i https://pkg.pr.new/@tanstack/react-query@9193

      @tanstack/react-query-devtools

      npm i https://pkg.pr.new/@tanstack/react-query-devtools@9193

      @tanstack/react-query-next-experimental

      npm i https://pkg.pr.new/@tanstack/react-query-next-experimental@9193

      @tanstack/react-query-persist-client

      npm i https://pkg.pr.new/@tanstack/react-query-persist-client@9193

      @tanstack/solid-query

      npm i https://pkg.pr.new/@tanstack/solid-query@9193

      @tanstack/solid-query-devtools

      npm i https://pkg.pr.new/@tanstack/solid-query-devtools@9193

      @tanstack/solid-query-persist-client

      npm i https://pkg.pr.new/@tanstack/solid-query-persist-client@9193

      @tanstack/svelte-query

      npm i https://pkg.pr.new/@tanstack/svelte-query@9193

      @tanstack/svelte-query-devtools

      npm i https://pkg.pr.new/@tanstack/svelte-query-devtools@9193

      @tanstack/svelte-query-persist-client

      npm i https://pkg.pr.new/@tanstack/svelte-query-persist-client@9193

      @tanstack/vue-query

      npm i https://pkg.pr.new/@tanstack/vue-query@9193

      @tanstack/vue-query-devtools

      npm i https://pkg.pr.new/@tanstack/vue-query-devtools@9193

      commit: 2c1a713

    6. TkDodo reviewed

      @@ -48,7 +48,8 @@
      4848
      4949 **Parameter1 (Options)**
      5050
      51-- `mutationFn: (variables: TVariables) => Promise<TData>`
      51+- `mutationFn: (variables: TVariables, context: MutationFunctionContext) => Promise<TData>`
      5252 - **Required, but only if no default mutation function has been defined**
      5353 - A function that performs an asynchronous task and returns a promise.
      5454 - `variables` is an object that `mutate` will pass to your `mutationFn`
      55+ - `context` is an object that `mutate` will pass to your `mutationFn`. Contains reference to `QueryClient`, `mutationKey` and optional `meta` object.
      TkDodocommented

      there’s one more thing that’s a bit troubling, and that’s the fact that we already refer to something as “context” for mutations: The value that gets returned from onMutate, which can be seen in this example here:

      https://tanstack.com/query/v5/docs/framework/react/guides/optimistic-updates#updating-a-list-of-todos-when-adding-a-new-todo

      and in code here:

      https://github.com/TanStack/query/blob/02c3d5130e063c5f623adbfaf9bd986273b615cc/packages/query-core/src/mutation.ts#L29

      since it’s part of the public MutationState, which is available via useMutationState, we can’t just rename this, so it’s a bit unfortunate.

      Any ideas ?

      Given that the equivalent object in queryFn is already called context, it seems the trade off is consistency with QueryFunctionContext context vs a conflict with MutationState context.

      One idea is to rename the QueryFunctionContext to something else and name this new mutation function context accordingly. Examples:

      • QueryFunctionParams and MutationFunctionParams
      • QueryFunctionInfo and MutationFunctionInfo
      • QueryFunctionExecutionContext and MutationFunctionExecutionContext
      • QueryFunctionDetails and MutationFunctionDetails
      • QueryFunctionMetaContext and MutationFunctionMetaContext

      This way we get consistency between queryFn and mutationFn, but eliminate the conflict with MutationState.

      Honestly I don't love any of these, but I think the root of that issue is that these objects and the context in MutationState are both most accurately described as a "context".

      @travikk light bump on this!

      Hey apologies for missing the updates.

      Yeah, I totally agree with @solastley here. There doesn't seem to be a preferred way forward here, but there's clearly a benefit in having consistency in API between queryFn and mutateFn in that we can access QueryCache or QueryClient from both.

      Can we perhaps bet on a slightly tuned/better documentation to distinguish between mutateFn context proposed here and return value of onMutate?

      @TkDodo do you mind weighing in?

      TkDodocommented

      would it be a breaking change to rename the return value of onMutate to something else? After all, it’s just as positional argument. I never liked context for this...

      How about calling it scope?

      mutationFn(vars, context) {
         if (context.meta.something) {
           // ...
         }
         return fetch('...');
      },
      onMutate(_vars, context) {
        if (context.client) {
           // ...
        }
        const scope = {foo: 'bar'}
        return scope;
      },
      onSuccess(_data, _vars, scope) {
        console.log(scope)
      }
      TkDodocommented

      @Rendez let’s do it 👍

    7. We're quite interested in utilising this new feature at Sanity as part of our own abstraction for a SanityQueryClient – is there anything to do to help push this PR forward? Is it just the naming of context vs scope or more...?

    8. TkDodocommented

      @joshuaellis I’m fine with the scope renaming of what gets returned from onMutate. Then, we can have context for what gets passed to the mutationFn as second argument. I think it just needs to be done. If you want to open another PR to get it over the finish line, please do.

    9. TkDodo closed this

Sign in to join this conversation.