T
TanStack7mo ago
sensitive-blue

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());
}
},
}),
);
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.
2 Replies
plain-purple
plain-purple7mo ago
Is it a client side navigation? Are you reloading the entire site?
sensitive-blue
sensitive-blueOP7mo ago
its client side navigation i expect the data to have been optimistically updated since its client side but its not

Did you find this page helpful?