Skip to content

Commit

Permalink
Merge pull request #65 from udohjeremiah/dev
Browse files Browse the repository at this point in the history
Fix error on upvote/downvote functionality.
  • Loading branch information
udohjeremiah authored Feb 16, 2025
2 parents 2f89f3a + 81cac7d commit 1634e38
Showing 1 changed file with 22 additions and 10 deletions.
32 changes: 22 additions & 10 deletions src/app/api/answers/[id]/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -172,19 +172,31 @@ export async function PATCH(request, { params }) {
);
}

// Check if the user has voted before
const existingVote = upvotesHistory.find((item) => item.id === userId);
if (existingVote) {
// user has upvoted or downvoted before
updateFields.upvotes =
upvotesDirection === "up" ? upvotes - 1 : upvotes + 1;

updateFields.upvotesHistory = upvotesHistory.map((item) =>
item.id === userId
? { id: userId, direction: upvotesDirection }
: item,
);
if (existingVote) {
if (existingVote.direction === upvotesDirection) {
// If the vote direction is the same as the current, remove it (toggle)
updateFields.upvotes =
upvotesDirection === "up" ? upvotes - 1 : upvotes + 1;

updateFields.upvotesHistory = upvotesHistory.filter(
(item) => item.id !== userId,
);
} else {
// If the vote direction is different, toggle it (upvote -> downvote or vice versa)
updateFields.upvotes =
upvotesDirection === "up" ? upvotes + 1 : upvotes - 1;

updateFields.upvotesHistory = upvotesHistory.map((item) =>
item.id === userId
? { id: userId, direction: upvotesDirection }
: item,
);
}
} else {
// user has not upvoted or downvoted before
// If the user has not voted before, add their vote
updateFields.upvotes =
upvotesDirection === "up" ? upvotes + 1 : upvotes - 1;

Expand Down

0 comments on commit 1634e38

Please sign in to comment.