T
TanStack•12mo ago
fair-rose

Why is `isMutating` positive once `onSettled` is called?

Hey there 👋 I am currently attempting to update query data with the result of a mutation, but I only want to do this assuming there are no in-flight mutations. However, when I check the isMutating state of the mutation once onSettled has been called, I find that it is always at least one, even if there was only 1 mutation executed. At this point, I would assume that the mutation would not be considered "mutating" any longer. Does anyone know why this might be? Bonus: here is what I am attempting to do if you have any suggestions!
const { mutate: handleReaction } = trpc.post.handleReaction.useMutation({
onMutate: async () => {
console.log(
"onMutate isMutating",
utils.post.handleReaction.isMutating(),
);
startTransition(() => {
if (onReaction) onReaction(reactionTypeId, emoji, emojiName, isReacted);
});
},
onSuccess: (data) => {
console.log(
"onSuccess isMutating",
utils.post.handleReaction.isMutating(),
);
if (utils.post.handleReaction.isMutating()) return; // Prevent query update if there are in-flight mutations
console.log("updating");
utils.post.getPostReactions.setData({ postId }, data);
},
onSettled: (data) => {
console.log(
"onSettled isMutating",
utils.post.handleReaction.isMutating(),
);
},
});
const { mutate: handleReaction } = trpc.post.handleReaction.useMutation({
onMutate: async () => {
console.log(
"onMutate isMutating",
utils.post.handleReaction.isMutating(),
);
startTransition(() => {
if (onReaction) onReaction(reactionTypeId, emoji, emojiName, isReacted);
});
},
onSuccess: (data) => {
console.log(
"onSuccess isMutating",
utils.post.handleReaction.isMutating(),
);
if (utils.post.handleReaction.isMutating()) return; // Prevent query update if there are in-flight mutations
console.log("updating");
utils.post.getPostReactions.setData({ postId }, data);
},
onSettled: (data) => {
console.log(
"onSettled isMutating",
utils.post.handleReaction.isMutating(),
);
},
});
2 Replies
fair-rose
fair-roseOP•12mo ago
If this is not possible, one alternative (which I have been using up until noiw) is to simply cancel the queries on the query I am updating and refetch the query when the mutation reached onSuccess or maybe onSettled. Edit: or obviously to just skip setting query data if isMutating is > 1.
exotic-emerald
exotic-emerald•12mo ago
I don't believe mutation status is updated until after all callbacks have run hence you seeing a 'pending', aka in flight, mutation isMutating > 1 should work but that would be any mutation in your queryClient. You might want to filter with a mutationKey

Did you find this page helpful?