"use client"; import { useEffect, useState } from "react"; import { api } from "@/trpc/react"; import { Comment } from "@/server/db/schema"; import { ADD_COMMENT_EVENT, DELETE_COMMENT_EVENT, } from "@/server/socket/event-const"; import { useSocket } from "@/components/socket-context"; export function useComments(articleId: string) { const [comments, setComments] = useState>([]); const { data } = api.comment.list.useQuery({ articleId }); const { socket } = useSocket(); useEffect(() => { if (!socket) return; console.log("useComments"); socket.on(DELETE_COMMENT_EVENT, (deletedCommentId) => { console.log("DELETE_COMMENT_EVENT:::client", deletedCommentId); setComments((prev) => prev?.filter((c) => c.id !== deletedCommentId)); }); socket.on(ADD_COMMENT_EVENT, (newComment: Comment) => { setComments((prev) => [newComment, ...prev]); }); return () => { socket.disconnect(); }; }, [socket]); useEffect(() => { if (data) { setComments(data); } }, [data]); return { comments }; }