Pavel Filo
Pavel Filo
TTCTheo's Typesafe Cult
Created by Pavel Filo on 12/4/2023 in #questions
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?
5 replies