import { zodResolver } from '@hookform/resolvers/zod'; import { FC, useState, Dispatch, SetStateAction } from 'react'; import { Rating } from 'react-daisyui'; import { useForm, SubmitHandler } from 'react-hook-form'; import { z } from 'zod'; import useBeerPostComments from '@/hooks/data-fetching/beer-comments/useBeerPostComments'; import CommentQueryResult from '@/services/schema/CommentSchema/CommentQueryResult'; import CreateCommentValidationSchema from '@/services/schema/CommentSchema/CreateCommentValidationSchema'; import useBreweryPostComments from '@/hooks/data-fetching/brewery-comments/useBreweryPostComments'; import toast from 'react-hot-toast'; import createErrorToast from '@/util/createErrorToast'; import FormError from '../ui/forms/FormError'; import FormInfo from '../ui/forms/FormInfo'; import FormLabel from '../ui/forms/FormLabel'; import FormSegment from '../ui/forms/FormSegment'; import FormTextArea from '../ui/forms/FormTextArea'; interface EditCommentBodyProps { comment: z.infer; setInEditMode: Dispatch>; mutate: ReturnType< typeof useBeerPostComments | typeof useBreweryPostComments >['mutate']; handleDeleteRequest: (id: string) => Promise; handleEditRequest: ( id: string, data: z.infer, ) => Promise; } const EditCommentBody: FC = ({ comment, setInEditMode, mutate, handleDeleteRequest, handleEditRequest, }) => { const { register, handleSubmit, formState, setValue, watch } = useForm< z.infer >({ defaultValues: { content: comment.content, rating: comment.rating }, resolver: zodResolver(CreateCommentValidationSchema), }); const { errors, isSubmitting } = formState; const [isDeleting, setIsDeleting] = useState(false); const onDelete = async () => { const loadingToast = toast.loading('Deleting comment...'); setIsDeleting(true); try { await handleDeleteRequest(comment.id); await mutate(); toast.remove(loadingToast); toast.success('Deleted comment.'); } catch (error) { toast.remove(loadingToast); createErrorToast(error); } }; const onEdit: SubmitHandler> = async ( data, ) => { const loadingToast = toast.loading('Submitting comment edits...'); try { setInEditMode(true); await handleEditRequest(comment.id, data); await mutate(); toast.remove(loadingToast); toast.success('Comment edits submitted successfully.'); setInEditMode(false); } catch (error) { toast.remove(loadingToast); createErrorToast(error); setInEditMode(false); } }; return (
Edit your comment {errors.content?.message}
Change your rating {errors.rating?.message} { setValue('rating', value); }} > {Array.from({ length: 5 }).map((val, index) => ( ))}
); }; export default EditCommentBody;