TanStackT
TanStack9mo ago
3 replies
nursing-lime

Optimistic Update not working on another route.

On /vote/$senatorId I have a mutation
  const { mutateAsync } = useMutation(
    trpc.vote.addVote.mutationOptions({
      onMutate: async ({ sway }) => {
        const getAllVotesQF = trpc.vote.getAllVotes.queryFilter({ userId });
        await queryClient.cancelQueries(getAllVotesQF);
        const previousAllVotes = queryClient.getQueryData(getAllVotesQF.queryKey);
        if (previousAllVotes) {
          queryClient.setQueriesData(
            getAllVotesQF,
            previousAllVotes
              .map((v) => {
                if (v.senatorId === senatorLinkName) {
                  return {
                    ...v,
                    decision: sway,
                  };
                }
                return v;
              })
              .sort((a, b) => a.id - b.id),
          );
        }

        return { previousSenatorVote, previousAllVotes };
      },
      onSettled: async () => {
        if (queryClient.isMutating() === 1) {
          queryClient.invalidateQueries(trpc.vote.getSenatorVote.queryFilter());
          queryClient.invalidateQueries(trpc.vote.getAllVotes.queryFilter());
        }
      },
    }),
  );


My problem is, getAllVotes is used in another route at /myVotes and when I navigate directly after sending the mutation, the updates dont seem to be optimistically done, only when the invalidation finishes does the data change.
If I, however, copy consume the component from /myVotes to /vote/$senatorId, I can see the optimistic updates working, but again, when navigating it does not work immediately.

I guess what I'm trying to ask is, how do I properly optimistically update data on another route?
I'm not sure if this is a tanstack-start issue or a react-query issue or if it's a react thing in general.
Was this page helpful?