Skip to content

Commit

Permalink
fix: votes
Browse files Browse the repository at this point in the history
  • Loading branch information
nunocaseiro committed Jan 11, 2023
1 parent a75b876 commit dc2229e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
2 changes: 1 addition & 1 deletion frontend/src/components/Board/Card/CardFooter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ const CardFooter = React.memo<FooterProps>(
<StyledButtonIcon
disabled={
!isMainboard ||
user?.votesCount === maxVotes ||
(maxVotes && user?.votesCount === maxVotes) ||
(maxVotes && disableVotes.maxVotesReached) ||
(hideCards && createdBy?._id !== userId)
}
Expand Down
17 changes: 14 additions & 3 deletions frontend/src/hooks/useVotes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,13 @@ const useVotes = () => {
);
};

const getPrevData = async (id: string | undefined): Promise<BoardType | undefined> => {
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);

Expand Down Expand Up @@ -231,19 +238,23 @@ const useVotes = () => {
};

const updateVote = async (variables: VoteDto) => {
const { newBoardData } = await updateVoteOptimistic(
const { newBoardData, prevBoardData } = await updateVoteOptimistic(
variables.count > 0 ? Action.Add : Action.Remove,
variables,
);

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 }]);
Expand Down

0 comments on commit dc2229e

Please sign in to comment.