I have a graphQL API. That means I can customize whatever response I want from my mutations.
Of course, I need my UI to be in sync with fresh data. I'm not sure what would be the best option to accomplish that, though.
Option 1
https://react-query.tanstack.com/guides/invalidations-from-mutations
- Not return anything from the mutations other than a success status
- Use
invalidateQueries
to refetch related queries that should be stale after the mutation
Option 2
https://react-query.tanstack.com/guides/updates-from-mutation-responses
- Return the full mutated object from the mutation
- Use
setQueryData
to merge mutation response to current query data
What are the pros and cons of each a approach? Is one recommended of the other, when dealing with a graphQL backend?
React query seems to suggest that invalidateQueries
should be the best approach. See quote below. I mean, I can have the object returned from the mutation, but it's not something "automatic" in a graphQL flexible endpoint. You can choose.
When dealing with mutations that update objects on the server, it's common for the new object to be automatically returned in the response of the mutation. Instead of refetching any queries for that item and wasting a network call for data we already have, we can take advantage of the object returned by the mutation function and update the existing query with the new data immediately using the Query Client's setQueryData method:
I think that not returning from the mutations and using invalidateQueries
will make my mutations more simple and flexible, because they can be used in different contexts in invalidate different queries in each situation.
I guess that other then avoiding one extra network request, I don't see any other pros for going with Option 2.
This is for a React single page web app. What would be the best practice here?