T
TanStack3y ago
stormy-gold

Mutation -> Invalidation + Refetch or setQueryData

Currently in our app, we have a lot of scenarios where we do the following:
const mutation = useMutation(
(params) => {
return fetchFunction({
params
});
},
{
retry: 1,
onSuccess: async () => {
await queryClient.invalidateQueries(
[QUERY_KEYS],
{
refetchType: 'all',
}
);
refetch();
},
const mutation = useMutation(
(params) => {
return fetchFunction({
params
});
},
{
retry: 1,
onSuccess: async () => {
await queryClient.invalidateQueries(
[QUERY_KEYS],
{
refetchType: 'all',
}
);
refetch();
},
Having read around I am feeling that we could instead use setQueryData here in the onSuccess of the useMutation? What are the pros / cons of this, is there a recommended best practice where we update some data via a mutation and need our results immediately. (The queries would be 'active' but don't seem to fetch data until refocus / navigation after invalidation without the refetch call). Thanks!
5 Replies
solid-orange
solid-orange3y ago
Where is refetch coming from? Also: invalidateQueries is enough Use setQueryData to save a network call (slow API is a good use case)
stormy-gold
stormy-goldOP3y ago
refetching the get query that i left out for brevity (The same query we are invalidating). Without calling refetch the invalidation is either slow to refetch or doesn't refetch we need it to immediately display new data when it returns. Thus leading me toward setting query data.
foreign-sapphire
foreign-sapphire3y ago
If your POST request returns everything you need you can call setQueryData yourself, otherwise invalidateQueries would be your best option Invalidate also happens immediately so not sure about the slow part. Any slowness is probably caused by your GET response time
foreign-sapphire
foreign-sapphire3y ago
Mastering Mutations in React Query
Learn all about the concept of performing side effects on the server with React Query.
stormy-gold
stormy-goldOP3y ago
I think the 'slowness' is more so to do with the query states potentially not being 'active' as we use them in providers? But havent tracked this down yet, I think the setQueryData approach is best at the moment.

Did you find this page helpful?