import UserContext from '@/contexts/UserContext'; import { FC, MutableRefObject, useContext, useRef } from 'react'; import { z } from 'zod'; import { useRouter } from 'next/router'; import CreateCommentValidationSchema from '@/services/schema/CommentSchema/CreateCommentValidationSchema'; import BeerStyleQueryResult from '@/services/BeerStyles/schema/BeerStyleQueryResult'; import useBeerStyleComments from '@/hooks/data-fetching/beer-style-comments/useBeerStyleComments'; import LoadingComponent from '../BeerById/LoadingComponent'; import CommentsComponent from '../ui/CommentsComponent'; import BeerStyleCommentForm from './BeerStyleCommentForm'; interface BeerStyleCommentsSectionProps { beerStyle: z.infer; } const BeerStyleCommentsSection: FC = ({ beerStyle }) => { const { user } = useContext(UserContext); const router = useRouter(); const pageNum = parseInt(router.query.comments_page as string, 10) || 1; const PAGE_SIZE = 15; const { comments, isLoading, mutate, setSize, size, isLoadingMore, isAtEnd } = useBeerStyleComments({ id: beerStyle.id, pageNum, pageSize: PAGE_SIZE }); const commentSectionRef: MutableRefObject = useRef(null); const handleDeleteRequest = async (id: string) => { const response = await fetch(`/api/beer-style-comments/${id}`, { method: 'DELETE', }); if (!response.ok) { throw new Error('Failed to delete comment.'); } }; const handleEditRequest = async ( id: string, data: z.infer, ) => { const response = await fetch(`/api/beer-style-comments/${id}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ content: data.content, rating: data.rating }), }); if (!response.ok) { throw new Error(response.statusText); } }; return (
{user ? ( ) : (
Log in to leave a comment.
)}
{ /** * If the comments are loading, show a loading component. Otherwise, show the * comments. */ isLoading ? (
) : ( ) }
); }; export default BeerStyleCommentsSection;