Pass callbacks for onSuccess, onError and onSettled to each custom hook?
I have a custom hook for each api call my application makes. I wrap the api call with either useQuery or useMutation. The issue is, I need to handle each scenrio that results from that api call. To do this, I am passing callbacks for onSuccess, onError and onSettled to the custom hook. I'm trying to figure out if this is how react-query is intended to be used. Or what the standard / best practice is in this regard?
Would it be better to not wrap each of my api calls with the hooks from react-query in my api.ts file? And instead just have the plain api calls. Then whenever I want to call an api endpoint I use the useQuery or useMutation hooks to wrap that api call? That would mean I can pass my callbacks directly to the react-query hook callbacks.
4 Replies
dependent-tan•3y ago
These callbacks are gone in v5 for useQuery
adverse-sapphireOP•3y ago
true but what about for useMutation?
Is it ok to pass those callbacks to my custom hook each time?
optimistic-gold•3y ago
Put "must-run" or global side effects like query invalidation in the callbacks on usemutation in your custom hook.
Pass context-specific side effects like triggering a navigation to the options param on .mutate when calling it. There's no need allow the forwarding of useMutation options into your custom hook I imagine
adverse-sapphireOP•3y ago
That seems like a very sensible approach! Thanks @Heartless
Yes, did not realise that until just now!