Skip to content

Commit

Permalink
Implemented delete comment functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
mbeps committed Feb 20, 2023
1 parent 282d531 commit 902d371
Showing 1 changed file with 32 additions and 2 deletions.
34 changes: 32 additions & 2 deletions src/components/Posts/Comments/Comments.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ const Comments: React.FC<CommentsProps> = ({
const [comments, setComments] = useState<Comment[]>([]);
const [fetchLoading, setFetchLoading] = useState(true);
const [createLoading, setCreateLoading] = useState(false);
const [loadingDelete, setLoadingDelete] = useState("");
const setPostState = useSetRecoilState(postState);

const onCreateComment = async () => {
Expand Down Expand Up @@ -86,7 +87,36 @@ const Comments: React.FC<CommentsProps> = ({
setCreateLoading(false);
}
};
const onDeleteComment = async (comment: any) => {};
const onDeleteComment = async (comment: Comment) => {
setLoadingDelete(comment.id);
try {
const batch = writeBatch(firestore);

const commentDocRef = doc(firestore, "comments", comment.id);
batch.delete(commentDocRef);

const postDocRef = doc(firestore, "posts", selectedPost?.id!);
batch.update(postDocRef, {
numberOfComments: increment(-1),
});

await batch.commit();

setPostState((prev) => ({
...prev,
selectedPost: {
...prev.selectedPost,
numberOfComments: prev.selectedPost?.numberOfComments! - 1,
} as Post,
}));

setComments((prev) => prev.filter((item) => item.id !== comment.id));
} catch (error) {
console.log("Error: onDeleteComment");
} finally {
setLoadingDelete("");
}
};
const getPostComments = async () => {
try {
const commentsQuery = query(
Expand Down Expand Up @@ -159,7 +189,7 @@ const Comments: React.FC<CommentsProps> = ({
key={comment.id}
comment={comment}
onDeleteComment={onDeleteComment}
loadingDelete={false}
loadingDelete={loadingDelete === comment.id}
userId={user.uid}
/>
))}
Expand Down

0 comments on commit 902d371

Please sign in to comment.