When to refetch query after mutation?

I have question regarding refetching queries. Take this as a basic example:
const queryClient = useQueryClient()

const { data } = useQuery({
queryKey: ['stuff'],
queryFn: () => fetchStuff(),
})

const insertMutation = useMutation({
mutationFn: (variables) =>
insertStuff(variables),
onSuccess: async (response) => {
if (response.data) {
await queryClient.cancelQueries({ queryKey: ['stuff'] })
const cacheData = queryClient.getQueryData([
'stuff',
])
if (cacheData) {
queryClient.setQueryData(['stuff'], {
data: {
vehicles: [response.data, ...cacheData.data.stuff],
},
})
}
}
},
})
const queryClient = useQueryClient()

const { data } = useQuery({
queryKey: ['stuff'],
queryFn: () => fetchStuff(),
})

const insertMutation = useMutation({
mutationFn: (variables) =>
insertStuff(variables),
onSuccess: async (response) => {
if (response.data) {
await queryClient.cancelQueries({ queryKey: ['stuff'] })
const cacheData = queryClient.getQueryData([
'stuff',
])
if (cacheData) {
queryClient.setQueryData(['stuff'], {
data: {
vehicles: [response.data, ...cacheData.data.stuff],
},
})
}
}
},
})
is it okay to just add an item to the cache without refetching the original query? another case is when I have optimisticUpdate included, is it okay if I change something and when mutation throws error I will just bring back the last data into the cache without refetching the query? What is the best approach towards this problem?
Solution:
the main advantage of refetch is that it’s less error prone and there’s a higher probability your cache matches the server. it’s easier to just refetch than manually update the cache update locally and not refetch has the advantage of not taxing your server if you’re confident the cache is gonna be what it should be there’s no best approach in general for this, you should do what you think makes sense for your use case...
Jump to solution
2 Replies
Solution
isaac_way
isaac_way6mo ago
the main advantage of refetch is that it’s less error prone and there’s a higher probability your cache matches the server. it’s easier to just refetch than manually update the cache update locally and not refetch has the advantage of not taxing your server if you’re confident the cache is gonna be what it should be there’s no best approach in general for this, you should do what you think makes sense for your use case
Manupa Samarawickrama
Why are u manually mutating instad of queryClient.invalidateQueries