From dc2229ef896c1e181e30d1df603e6d854058d034 Mon Sep 17 00:00:00 2001 From: Nuno Caseiro Date: Wed, 11 Jan 2023 18:12:17 +0000 Subject: [PATCH] fix: votes --- .../src/components/Board/Card/CardFooter.tsx | 2 +- frontend/src/hooks/useVotes.tsx | 17 ++++++++++++++--- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/frontend/src/components/Board/Card/CardFooter.tsx b/frontend/src/components/Board/Card/CardFooter.tsx index b00f3a561..3e06d3345 100644 --- a/frontend/src/components/Board/Card/CardFooter.tsx +++ b/frontend/src/components/Board/Card/CardFooter.tsx @@ -205,7 +205,7 @@ const CardFooter = React.memo( { ); }; + const getPrevData = async (id: string | undefined): Promise => { + const query = getBoardQueryKey(id); + await queryClient.cancelQueries(query); + const prevData = queryClient.getQueryData<{ board: BoardType }>(query); + return prevData?.board; + }; + const getFirstCardItemIndexWithVotes = (cardItems: CardItemType[]) => cardItems.findIndex((cardItem) => cardItem.votes.length > 0); @@ -231,7 +238,7 @@ const useVotes = () => { }; const updateVote = async (variables: VoteDto) => { - const { newBoardData } = await updateVoteOptimistic( + const { newBoardData, prevBoardData } = await updateVoteOptimistic( variables.count > 0 ? Action.Add : Action.Remove, variables, ); @@ -239,11 +246,15 @@ const useVotes = () => { if (newBoardData?.maxVotes && variables.userId === userId) { toastRemainingVotesMessage('', newBoardData); } + + return { newBoardData, prevBoardData }; }; const handleVote = useMutation(handleVotes, { - onSuccess: async (data, variables) => { - updateVote(variables); + onMutate: async (variables) => { + const { newBoardData, prevBoardData } = await updateVote(variables); + + return { previousBoard: prevBoardData, data: newBoardData }; }, onError: (_, variables, context) => { queryClient.invalidateQueries(['board', { id: variables.boardId }]);