TanStackT
TanStack9mo ago
4 replies
nursing-lime

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());
      },
    }),
  );

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.
e0vmZ6fgA7.gif
Was this page helpful?