From 950646a42692bdd749766b4ba17544fb6ecb0afc Mon Sep 17 00:00:00 2001 From: Mathis HERRIOT <197931332+0x485254@users.noreply.github.com> Date: Thu, 29 Jan 2026 15:55:39 +0100 Subject: [PATCH] feat: add WebSocket integration for live comment updates - Introduced `useSocket` to manage WebSocket connections in comment sections. - Implemented real-time comment updates via `new_comment` WebSocket events. - Added auto-join and leave for content-specific rooms using WebSocket upon mounting/unmounting. --- frontend/src/components/comment-section.tsx | 22 +++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/frontend/src/components/comment-section.tsx b/frontend/src/components/comment-section.tsx index 5a6f306..2119fb0 100644 --- a/frontend/src/components/comment-section.tsx +++ b/frontend/src/components/comment-section.tsx @@ -16,6 +16,7 @@ import { import { Textarea } from "@/components/ui/textarea"; import { cn } from "@/lib/utils"; import { useAuth } from "@/providers/auth-provider"; +import { useSocket } from "@/providers/socket-provider"; import { type Comment, CommentService } from "@/services/comment.service"; interface CommentSectionProps { @@ -24,6 +25,7 @@ interface CommentSectionProps { export function CommentSection({ contentId }: CommentSectionProps) { const { user, isAuthenticated } = useAuth(); + const { socket } = useSocket(); const [comments, setComments] = React.useState([]); const [newComment, setNewComment] = React.useState(""); const [replyingTo, setReplyingTo] = React.useState(null); @@ -45,6 +47,26 @@ export function CommentSection({ contentId }: CommentSectionProps) { fetchComments(); }, [fetchComments]); + // Gestion du WebSocket + React.useEffect(() => { + if (socket) { + socket.emit("join_content", contentId); + + socket.on("new_comment", (comment: Comment) => { + setComments((prev) => { + // Éviter les doublons si l'auteur reçoit son propre commentaire via WS + if (prev.some((c) => c.id === comment.id)) return prev; + return [comment, ...prev]; + }); + }); + + return () => { + socket.emit("leave_content", contentId); + socket.off("new_comment"); + }; + } + }, [socket, contentId]); + const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (!newComment.trim() || isSubmitting) return;