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.
This commit is contained in:
Mathis HERRIOT
2026-01-29 15:55:39 +01:00
parent a9b80e66cd
commit 950646a426

View File

@@ -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<Comment[]>([]);
const [newComment, setNewComment] = React.useState("");
const [replyingTo, setReplyingTo] = React.useState<Comment | null>(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;