query icon indicating copy to clipboard operation
query copied to clipboard

fix(query-core): Change to prevent `undefined` from overriding Mutation default side effects.

Open mitchell-up opened this issue 1 year ago • 2 comments

Problem

undefined means a variable that has not been assigned. Therefore, when the onError property in useMutation receives undefined, the side effects of the default options are retained and are expected to be invoked, as in the below example. However, It overrides default onError to undefined.

// You can pass `onError` callback optionally.
// If you intend to retain default `onError` callback,
// you will invoke this hook without any parameters.
const useLogin = (onError?) => {
 return useMutation({
    mutationFn: login,
    onError: onError,
    meta: {
      showToast: true,
    },
  })
}
// But if the useLogin is called without its parameters,
// default `onError` options will not be triggered.
new QueryClient({
  defaultOptions: {
    // ...
    mutations: {
      onError(error) {
        if (isHttpError(error)) {
          defaultErrorHandlers(error)
        }
      },
    },
  },
}),

Suggestion

To clarify the intention of not using side effects of default options, assign null to the side effects. Because null means absence of any value, you can predict that the side effects will not be invoked.

const useLogin = (onError?) => {
 return useMutation({
    mutationFn: login,
    onError: onError,
    meta: {
      showToast: true,
    },
  })
}

// This `mutate` call will not trigger any `onError` side effects, including the default `onError`.
const { mutate } = useLogin(null)

// This `mutate` call will not trigger the default `onError`, but `errorHandler` will be called.
const { mutate } = useLogin(errorHandler)

// These `mutate` calls will trigger the default `onError`.
const { mutate } = useLogin()
const { mutate } = useLogin(undefined)

mitchell-up avatar Jun 14 '24 15:06 mitchell-up

The latest updates on your projects. Learn more about Vercel for Git ↗︎

1 Ignored Deployment
Name Status Preview Comments Updated (UTC)
query ⬜️ Ignored (Inspect) Visit Preview Jun 14, 2024 3:50pm

vercel[bot] avatar Jun 14 '24 15:06 vercel[bot]

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

Latest deployment of this branch, based on commit 720cd959c61eb12a35071f0d93a58fc83b49c7e7:

Sandbox Source
@tanstack/query-example-angular-basic Configuration
@tanstack/query-example-react-basic-typescript Configuration
@tanstack/query-example-solid-basic-typescript Configuration
@tanstack/query-example-svelte-basic Configuration
@tanstack/query-example-vue-basic Configuration

codesandbox-ci[bot] avatar Jun 14 '24 15:06 codesandbox-ci[bot]

we don’t do this anywhere with our options so we’re not gonna make an exception here, sory.

TkDodo avatar May 04 '25 10:05 TkDodo