Added part of RequestComment Component

master
YasamanKahdooei 2024-05-25 16:34:12 +03:30
parent cc5f57fdf2
commit da8fd4a1ca
3 changed files with 214 additions and 46 deletions

View File

@ -0,0 +1,96 @@
"use client";
import React from "react";
import { convertFullTime } from "@/lib/utils";
import RequestViolation from "./RequestViolation";
import { BsTrash3 } from "react-icons/bs";
import ph from "@/assets/images/ph.png";
import Image from "next/image";
import { useMutation } from "@tanstack/react-query";
import { deleteComment } from "@/utils/CitizenReport";
import { toast } from "sonner";
interface RequestCommentProps {
id: string;
comment: string;
dateTime: string;
user: any;
canDelete: boolean;
}
const getUserTitle = (user: any) => {
if (user.firstName || user.lastName)
return `${user.firstName || ""} ${user.lastName || ""}`;
else if (user.title) return user.title;
else return "شهروند";
};
const RequestComment: React.FC<RequestCommentProps> = ({
id,
comment,
dateTime,
user,
canDelete,
}) => {
const DeleteComment = useMutation({
mutationKey: ["deleteComment"],
mutationFn: deleteComment,
onSuccess: (res) => {
toast(<>{res.message}</>, {
className: "!bg-green !text-black",
});
},
onError: (error: any | string) => {
toast(<>{error.message}</>, {
className: "!bg-red-500 !text-white",
});
},
});
const handelDelete = () => {
DeleteComment.mutate(id);
};
return (
<div className="flex w-full items-stretch mb-3 p-2 border-b-[1px] border-b-gray-200 last:border-b-0">
<div className="w-12 h-12 ml-2">
<Image
className="object-cover rounded-full w-full h-full"
alt="picture"
quality={100}
height={50}
width={50}
src={
user?.avatar?.url3
? `${process.env.NEXT_PUBLIC_BASE_URL_APP}${user?.avatar?.url3}`
: ph
}
/>
</div>
<div className="flex flex-1 flex-col">
<div className="flex w-full items-center justify-between">
<p className="text-xs font-bold text-gray-500">
{getUserTitle(user)}
</p>
<span className="text-xs font-bold text-gray-500">
{convertFullTime(dateTime)}
</span>
</div>
<div className="flex flex-1 items-center justify-between">
<p
className="flex flex-1 text-justify text-sm text-black"
style={{ lineBreak: "anywhere" }}
>
{comment}
</p>
{canDelete && (
<BsTrash3 className="text-red" onClick={handelDelete} />
)}
<RequestViolation />
</div>
</div>
</div>
);
};
export default RequestComment;

View File

@ -1,7 +1,7 @@
"use client";
import { getComments } from "@/utils/CitizenReport";
import { useQuery } from "@tanstack/react-query";
import React, { useState } from "react";
import { getComments, postComment } from "@/utils/CitizenReport";
import { useMutation, useQuery } from "@tanstack/react-query";
import React, { useEffect, useState } from "react";
import { FaRegComment } from "react-icons/fa";
import {
Drawer,
@ -16,6 +16,9 @@ import {
import { Button } from "../ui/button";
import { MdSend } from "react-icons/md";
import { Textarea } from "../ui/textarea";
import { toast } from "sonner";
import { Oval, ThreeDots } from "react-loader-spinner";
import RequestComment from "./RequestComment";
// Define types for props
interface RequestCommentsProps {
@ -23,47 +26,69 @@ interface RequestCommentsProps {
commentsCount: number;
}
// Define types for comments
interface Comment {
id: string;
text: string;
dateTime: string;
user:any;
canDelete:boolean;
}
// Define the post comment function type
type PostCommentArgs = {
id: string;
comment: string;
};
const RequestComments: React.FC<RequestCommentsProps> = ({
reportId,
commentsCount,
}) => {
// Component state
const [comments, setComments] = useState<Comment[]>([]);
const [commentsCounts, setCommentsCounts] = useState<number>(commentsCount);
const [comment, setComment] = useState("");
const [commentText, setCommentText] = useState("");
const { data, isLoading, isError, isSuccess, refetch } = useQuery({
queryKey: ["Comments"],
queryKey: ["Comments", reportId],
queryFn: () => getComments(reportId),
// refetchOnWindowFocus: false,
});
const handleSubmit = async (event: React.FormEvent) => {
event.preventDefault();
const requestBody = {
comment: comment,
};
try {
const response = await fetch(`/api/comments/${reportId}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(requestBody),
});
if (!response.ok) {
throw new Error("Network response was not ok");
}
// Handle success (e.g., clear the input, show a success message, etc.)
setComment("");
console.log("Comment submitted successfully!");
} catch (error) {
// Handle error
console.error("There was an error submitting the comment:", error);
useEffect(() => {
console.log("Fetched data:", data); // Log the fetched data
if (data) {
setComments(data.data);
console.log("Comments state updated:", data);
}
}, [data]);
// Post Commnet
const mutation = useMutation({
mutationFn: ({ id, comment }: PostCommentArgs) => postComment(id, comment),
onSuccess: () => {
// Refetch comments after a new one is added
refetch();
// Reset the comment input field
setCommentText("");
// Increment the comments count
setCommentsCounts((prevCount) => prevCount + 1);
toast("successfully", {
className: "!bg-green !text-black",
});
},
onError: (error) => {
console.error("Failed to post comment:", error);
toast(<>{error.message}</>, {
className: "!bg-red-500 !text-white",
});
},
});
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
mutation.mutate({ id: reportId, comment: commentText });
};
return (
@ -73,25 +98,66 @@ const RequestComments: React.FC<RequestCommentsProps> = ({
<DrawerTrigger onClick={(e) => e.stopPropagation()}>
<FaRegComment className="mx-1 cursor-pointer" />
</DrawerTrigger>
<DrawerContent className="bg-rose-400 px-64">
<DrawerHeader className="bg-yellow">
<p>
هنوز نظری برای این درخواست ثبت نشده است.
</p>
<DrawerContent className=" px-64">
<DrawerHeader className="">
{isLoading && (
<div className="flex justify-center items-center text-center w-full h-full">
<ThreeDots
visible={true}
height="50"
width="50"
color="#003778"
radius="9"
ariaLabel="three-dots-loading"
wrapperStyle={{}}
wrapperClass=""
/>
</div>
)}
{isError && <p>Failed to load comments.</p>}
{isSuccess && comments.length > 0 && commentsCounts > 0 ? (
<div>
{comments.map((comment) => (
<>
{console.log(comment)}
<RequestComment
key={comment.id}
id={comment.id}
comment={comment.text}
dateTime={comment.dateTime}
user={comment.user}
canDelete={comment.canDelete}
/>
</>
))}
</div>
) : (
!isLoading && <p>هنوز نظری برای این درخواست ثبت نشده است.</p>
)}
</DrawerHeader>
<form
onSubmit={handleSubmit}
className="flex justify-between bg-blue"
>
<form onSubmit={handleSubmit} className="flex justify-between">
<button type="submit" className="ml-2">
<MdSend />
{mutation.isPending ? (
<Oval
visible={true}
height="20"
width="20"
color="#000"
ariaLabel="oval-loading"
wrapperStyle={{}}
wrapperClass=""
/>
) : (
<MdSend className="w-5 h-5 text-green"/>
)}
</button>
<Textarea
placeholder="نظر جدید..."
className="w-full min-h-5"
onChange={(e) => setComment(e.target.value)}
className="resize-y w-full min-h-5 bg-white h-10 mb-4"
onChange={(e) => setCommentText(e.target.value)}
id="comment"
value={comment}
value={commentText}
/>
{/* <input
className="w-full pr-10"
@ -103,11 +169,11 @@ const RequestComments: React.FC<RequestCommentsProps> = ({
/> */}
</form>
<DrawerFooter>
{/* <DrawerFooter>
<DrawerClose>
<Button variant="outline">Cancel</Button>
</DrawerClose>
</DrawerFooter>
</DrawerFooter> */}
</DrawerContent>
</Drawer>
</span>

View File

@ -122,3 +122,9 @@ export async function getComments(id: string) {
const data = await axios.get(`/api/CitizenReport/Comments/${id}`);
return data.data;
}
// Delete CitizenReport Comment {id}
export async function deleteComment(id: string) {
const data = await axios.delete(`/api/CitizenReport/Comment/${id}`);
return data.data;
}