Skip to content

useMutation callbacks context type depends on options object sorting #8988

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
alexw-at opened this issue Apr 10, 2025 · 4 comments
Open

useMutation callbacks context type depends on options object sorting #8988

alexw-at opened this issue Apr 10, 2025 · 4 comments

Comments

@alexw-at
Copy link

Describe the bug

The type of context in the useMutation callbacks depends on the sorting of the options object.

Your minimal, reproducible example

https://codesandbox.io/p/devbox/usemutationcontext-qsnk89

Steps to reproduce

  1. Open minimal reproduction
  2. Open file src/index.tsx or run tsc --noemit
  3. Type of context in callbacks depends options object sorting
  4. first useMutation works as intended, second useMutation has type errors

Expected behavior

The type of context in useMutation callbacks should always be the same and not depend on the options object sorting.

How often does this bug happen?

Every time

Screenshots or Videos

No response

Platform

Seems to be a types only bug. Has no effect on runtime values.

Tanstack Query adapter

react-query

TanStack Query version

5.72.2

TypeScript version

5.8.2

Additional context

No response

@HanhNguyenHong1802
Copy link

Should you define type for it first? Like this

  const { mutate: mutate2 } = useMutation<
    void,
    unknown,
    string,
    { foo: string }
  >({
    mutationFn: async (value: string) => {
      console.log(value);
    },
    onError: (_error, _variables, context) => {
      console.log("onError", context?.foo);
    },
    onSettled: (_data, _error, _variables, context) => {
      console.log("onSettled", context?.foo);
    },
    onMutate: (data) => {
      return { foo: data };
    },
  });

Then the type error will disappear

@alexw-at
Copy link
Author

Yes this does work and the error disappears. But the inference of TContext still depends on the sorting of the options object.

@TkDodo
Copy link
Collaborator

TkDodo commented Apr 11, 2025

In an object, type consumers must come after type producers. onMutate produces the type, onError and onSettled consume them. This is a known typescript limitation:

. microsoft/TypeScript#53018 (comment)

We do have an eslint rule for infinite-query-property-order. @schiller-manuel do you think it would be possible to extend this to a more general rule that also covers this use-case?

@alexw-at
Copy link
Author

Thanks for the clarification. An eslint rule would be a nice.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants