Staying DRY and organised with react-query and CRUD operations #2349
Replies: 2 comments
-
So here is where I got to. I came across this thread (https://stackoverflow.com/questions/66427968/how-to-handle-multiple-queries-with-react-query) and see that useQueries is the way to go with multiple queries. With mutations my current approach is a custom hook that wraps multiple useMutation hooks, e.g.:
My only hesitation was that in my case some mutations are used rarely whereas some frequently - but I'm picking the overhead of having all the hooks initialised is small? Seems better to have all in one place. |
Beta Was this translation helpful? Give feedback.
-
mutations can have a default mutateFn as well, not sure if also in the queryClient, but at least via setMutationDefaults. So if they are all the same, you can make e.g. one generic one for delete, one for put etc. advantage over doing it manually for me are the callbacks, as well as react-query keeping track of mutation states (loading), so I can disable the submit button / show a loading spinner easily while the mutation is running. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I've recently discovered react-query and really like the query side of things. But I'm having trouble getting my head around the best way to organise mutations in an app that does a lot of data updating. Consider the following approach to exposing some operations:
So potentially there are two useQuery hooks there - but I don't think I need getById as I can do that in the component from the getAll. So my current hook looks a bit like this:
So if I did need a getById I'd create another custom hook - useQueryGetTodo? This seems fine and not too verbose.
However, when it comes to mutations - do I need to write half a dozen separate hooks for the create, delete, update, and any custom operations?
Is there some way of creating a single mutation wrapper with a switch statement, similar to redux or useReducer. Maybe something like:
The above works and keeps my logic out of my components, but what are the main benefits of react-query mutations as apposed to just doing your api operations then calling queryClient.setQueryData/invalidateQueries?
Is there a way to write a more generic hook with mutations rather than a hook for every operation?
Beta Was this translation helpful? Give feedback.
All reactions