cbdeveloper
cbdeveloper

Reputation: 31485

invalidateQueries vs setQueryData in graphQL mutations with react-query in a single page React app?

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

Option 2

https://react-query.tanstack.com/guides/updates-from-mutation-responses

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?

Upvotes: 2

Views: 1941

Answers (1)

cbdeveloper
cbdeveloper

Reputation: 31485

Just found a very nice post about it in the official docs.

https://react-query.tanstack.com/community/tkdodos-blog#12-mastering-mutations-in-react-query

Which links to:

https://tkdodo.eu/blog/mastering-mutations-in-react-query

enter image description here

I guess the default would be to just go with invalidateQueries and use setQueryData if you really have to.

Upvotes: 1

Related Questions