trpc / trpc

🧙‍♀️ Move Fast and Break Nothing. End-to-end typesafe APIs made easy.
https://tRPC.io
MIT License
34.6k stars 1.23k forks source link

feat: wanna default handle callback for `useMutation` in `react-query` #4924

Open moonrailgun opened 11 months ago

moonrailgun commented 11 months ago

Describe the feature you'd like to request

I wanna set a default global callback in trpc.

For example, i can has a default error alert tip if we throw error in request, or we have take mutation show operate success alert tip.

Now, i have to set those in every where.

I take a look of source code, its weird:

https://github.com/trpc/trpc/blob/42e6910cfb9f25ab12f522a3ede01a0078b5bc6d/packages/react-query/src/shared/hooks/createHooksInternal.tsx#L338-L370

Describe the solution you'd like to see

Set in trpc.createTRPCReact

export const trpc = createTRPCReact<AppRouter>({
  overrides: {
    useMutation: {
      onSuccess: ()=> console.log('success'),
    },
  },
});

or in new QueryClient

export const queryClient = new QueryClient({
  defaultOptions: {
    mutations: {
      onSuccess: () => console.log('success'),
      onError: () => console.log('error'),
    },
  },
});

Describe alternate solutions

none

Additional information

I want to contribute code to implement this feature, but i cant understand why there logic is it.

I'm not sure if this is intentional, can you give me some context?

👨‍👧‍👦 Contributing

Funding

Fund with Polar

lutefd commented 11 months ago

I am seeking clarification on the expected behavior when overriding a mutation. Specifically, is the expectation for the original function to be invoked first, followed by the global override? Or is the intention merely to adjust the way default options are passed? Right now it seems that if the override is defined in the router or query creation, only it gets called.

From the description provided, it seems logical for the original function to be called initially, given its closer association with the specific mutation. For instance, this would allow for the invalidation of a query pertaining to the specific mutation. Subsequently, the global override could be triggered to handle a broader operation, such as displaying a success alert.

Additionally, it might be beneficial to pass the result from the original function to the global override for further processing or for providing feedback. Is my understanding in line with the intended behavior?