T
TanStack•7mo ago
wise-white

How do you stop this behavior?

I have a mutation that looks like this.
const { mutateAsync } = useMutation(
trpc.vote.addVote.mutationOptions({
onMutate: async ({ sway }) => {
const qf = trpc.vote.getSenatorVote.queryFilter({ senatorId: senatorLinkName });
console.log(qf.queryKey);

await queryClient.cancelQueries(qf);
const previousSenatorVote = queryClient.getQueryData(qf.queryKey);

if (previousSenatorVote) {
queryClient.setQueryData(qf.queryKey, {
...previousSenatorVote,
decision: sway,
});
}

return { previousSenatorVote };
},
onSettled: () => {
queryClient.invalidateQueries(trpc.vote.getSenatorVote.queryFilter());
},
}),
);
const { mutateAsync } = useMutation(
trpc.vote.addVote.mutationOptions({
onMutate: async ({ sway }) => {
const qf = trpc.vote.getSenatorVote.queryFilter({ senatorId: senatorLinkName });
console.log(qf.queryKey);

await queryClient.cancelQueries(qf);
const previousSenatorVote = queryClient.getQueryData(qf.queryKey);

if (previousSenatorVote) {
queryClient.setQueryData(qf.queryKey, {
...previousSenatorVote,
decision: sway,
});
}

return { previousSenatorVote };
},
onSettled: () => {
queryClient.invalidateQueries(trpc.vote.getSenatorVote.queryFilter());
},
}),
);
Problem is, when I quickly click on the different answers(see gif), it does the laggy thing where the old onSettled catches up. I thought cancelling of the queries via await queryClient.cancelQueries(qf); would've stopped the previous invalidations.
No description
3 Replies
wise-white
wise-whiteOP•7mo ago
thanks, a lot. that's exactly what I was looking for
foreign-sapphire
foreign-sapphire•7mo ago
Concurrent Optimistic Updates in React Query
How to build optimistic UI that is resilient to race conditions, even when multiple mutations update the same entity concurrently.

Did you find this page helpful?