diff --git a/src/Web/Features/Contents/Handlers/AddReaction.cs b/src/Web/Features/Contents/Handlers/AddReaction.cs index 855ffa7..7097c36 100644 --- a/src/Web/Features/Contents/Handlers/AddReaction.cs +++ b/src/Web/Features/Contents/Handlers/AddReaction.cs @@ -48,43 +48,33 @@ public class AddReaction( { var content = await context.Contents.SingleAsync(x => x.Id == req.ContentId, ct); var reactionEnum = req.Reaction.ToEnum(); + var currentReaction = content.Reactions.SingleOrDefault(x => x.UserId == req.UserId); - var hasReacted = content.Reactions.Any(x => x.UserId == req.UserId); - - if (hasReacted) + // Already reacted or reaction didn't change, do nothing + if (currentReaction != null && currentReaction.Reaction == reactionEnum) { - var currentReaction = content.Reactions.Single(x => x.UserId == req.UserId); - if (currentReaction.Reaction == reactionEnum) return; - - if (reactionEnum.HasValue) - { - content.Reactions.Remove(currentReaction); - - var reaction = new ContentReaction - { - Reaction = reactionEnum.Value, - UserId = req.UserId, - UserName = req.UserName - }; - - content.Reactions.Add(reaction); - } + return; } - else + + // User has already reacted, remove the existing reaction + if (currentReaction != null) { - if (reactionEnum.HasValue) - { - var reaction = new ContentReaction - { - Reaction = reactionEnum.Value, - UserId = req.UserId, - UserName = req.UserName - }; - - content.Reactions.Add(reaction); - } + content.Reactions.Remove(currentReaction); } + // If the new reaction is valid, add or update the reaction + if (reactionEnum.HasValue) + { + var reaction = new ContentReaction + { + Reaction = reactionEnum.Value, + UserId = req.UserId, + UserName = req.UserName + }; + + content.Reactions.Add(reaction); + } + await context.SaveChangesAsync(ct); } }