Skip to content

Commit

Permalink
fixed bugs to do with comment count
Browse files Browse the repository at this point in the history
  • Loading branch information
vanesssalai committed Jul 10, 2024
1 parent bde5f3b commit 8284269
Show file tree
Hide file tree
Showing 2 changed files with 105 additions and 104 deletions.
101 changes: 54 additions & 47 deletions src/components/forumcards/ForumCards.jsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import React, { useEffect, useState } from "react";
import React, { useEffect, useState, useCallback } from "react";
import { useNavigate } from "react-router-dom";
import { useAuth } from "../../Auth";
import { FaPoll, FaRegHeart, FaHeart, FaShare } from "react-icons/fa";
import { FaCommentDots } from "react-icons/fa6";
import { doc, getDoc, updateDoc, setDoc, getDocs, addDoc, collection, query, where, deleteDoc} from 'firebase/firestore';
import { doc, getDoc, updateDoc, setDoc, getDocs, addDoc, collection, query, where, deleteDoc } from 'firebase/firestore';
import { db } from '../../lib/firebaseConfig';

import './ForumCards.css';

function timeSincePost(postDate) {
const now = new Date();
const now = new Date().toISOString();
const posted = new Date(postDate);
const diffInSeconds = Math.floor((now - posted) / 1000);

Expand Down Expand Up @@ -40,54 +40,58 @@ function ForumCards({ forumDetail }) {
const [selectedPollOption, setSelectedPollOption] = useState(null);
const [showResults, setShowResults] = useState(false);
const [isLiked, setIsLiked] = useState(false);
const [likeCount, setLikeCount] = useState(0);
const [likeCount, setLikeCount] = useState(forumDetail.likeCount || 0);
const [commentCount, setCommentCount] = useState(0);

useEffect(() => {
const fetchUser = async () => {
const fetchUser = useCallback(async () => {
if (!user) {
const userDocRef = doc(db, 'Users', forumDetail.userID);
const userDocSnap = await getDoc(userDocRef);

if (userDocSnap.exists()) {
setUser(userDocSnap.data());
}
};
}
}, [forumDetail.userID, user]);

const fetchAndCountComments = async () => {
const commentsRef = collection(db, 'Forum', forumDetail.id, 'Comments');
const commentsSnapshot = await getDocs(commentsRef);

const fetchedComments = await Promise.all(commentsSnapshot.docs.map(async doc => {
const comment = { id: doc.id, ...doc.data() };
const repliesRef = collection(db, 'Forum', forumDetail.id, 'Comments', doc.id, 'Replies');
const repliesSnapshot = await getDocs(repliesRef);
comment.replies = repliesSnapshot.docs.map(replyDoc => ({ id: replyDoc.id, ...replyDoc.data() }));
return comment;
}));
const checkLikeStatus = useCallback(async () => {
if (currentUser && !isLiked) {
const likesRef = collection(db, 'Forum', forumDetail.id, 'Likes');
const q = query(likesRef, where('userID', '==', currentUser.uid));
const querySnapshot = await getDocs(q);
setIsLiked(!querySnapshot.empty);
}
}, [currentUser, forumDetail.id, isLiked]);

const countCommentsAndReplies = (comments) => {
return comments.reduce((total, comment) => {
return total + 1 + (comment.replies ? countCommentsAndReplies(comment.replies) : 0);
}, 0);
};

const fetchCommentsRecursively = async (postID, parentRef = null) => {
const commentsQuery = parentRef
? query(collection(parentRef, 'Replies'))
: query(collection(db, 'Forum', postID, 'Comments'));
const commentsSnapshot = await getDocs(commentsQuery);

const fetchedComments = await Promise.all(commentsSnapshot.docs.map(async doc => {
const comment = { id: doc.id, ...doc.data() };
comment.replies = await fetchCommentsRecursively(postID, doc.ref);
return comment;
}));

if (!parentRef) {
const totalCount = countCommentsAndReplies(fetchedComments);
setCommentCount(totalCount);
};

const checkLikeStatus = async () => {
if (currentUser) {
const likesRef = collection(db, 'Forum', forumDetail.id, 'Likes');
const q = query(likesRef, where('userID', '==', currentUser.uid));
const querySnapshot = await getDocs(q);
setIsLiked(!querySnapshot.empty);
}
};

const getLikeCount = async () => {
const likesRef = collection(db, 'Forum', forumDetail.id, 'Likes');
const querySnapshot = await getDocs(likesRef);
setLikeCount(querySnapshot.size);
};
}

return fetchedComments;
};

useEffect(() => {
fetchUser();
checkLikeStatus();
getLikeCount();
fetchAndCountComments();
fetchCommentsRecursively(forumDetail.id);

if (currentUser) {
if (currentUser.uid === forumDetail.userID) {
Expand All @@ -106,7 +110,7 @@ function ForumCards({ forumDetail }) {
}
}
}
}, [forumDetail.id, forumDetail.userID, forumDetail.poll, currentUser]);
}, [forumDetail, currentUser, fetchUser, checkLikeStatus]);

const handleViewClick = () => {
trackClick();
Expand All @@ -129,18 +133,22 @@ function ForumCards({ forumDetail }) {
try {
await addDoc(collection(db, 'Forum', forumDetail.id, 'Likes'), {
userID: currentUser.uid,
timestamp: new Date()
timestamp: new Date().toISOString()
});
setIsLiked(true);
setLikeCount(prevCount => prevCount + 1);
const forumRef = doc(db, 'Forum', forumDetail.id);
await updateDoc(forumRef, {
likeCount: likeCount + 1
});

await addDoc(collection(db, 'Notifications'), {
recipientID: forumDetail.userID,
senderID: currentUser.uid,
listingID: forumDetail.id,
type: 'forum-like',
read: false,
timestamp: new Date()
timestamp: new Date().toISOString()
});
} catch (err) {
console.error("Error liking post:", err.message);
Expand All @@ -161,6 +169,11 @@ function ForumCards({ forumDetail }) {

setIsLiked(false);
setLikeCount(prevCount => prevCount - 1);

const forumRef = doc(db, 'Forum', forumDetail.id);
await updateDoc(forumRef, {
likeCount: likeCount - 1
});
} catch (err) {
console.error("Error unliking post:", err.message);
}
Expand Down Expand Up @@ -209,7 +222,7 @@ function ForumCards({ forumDetail }) {
}

const getWeekStart = () => {
const now = new Date();
const now = new Date().toISOString();
const dayOfWeek = now.getDay();
const diff = now.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1);
return new Date(now.setDate(diff)).setHours(0, 0, 0, 0);
Expand Down Expand Up @@ -269,12 +282,6 @@ function ForumCards({ forumDetail }) {
}
};

const countCommentsAndReplies = (comments) => {
return comments.reduce((total, comment) => {
return total + 1 + (comment.replies ? countCommentsAndReplies(comment.replies) : 0);
}, 0);
};

const tagColors = {
"Questions": "#FF4B2B",
"Modding": "#4CAF50",
Expand Down
108 changes: 51 additions & 57 deletions src/pages/forumpost/ForumPost.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -127,71 +127,65 @@ function ForumPostPage() {
const commentTextareaRef = useRef(null);
const [dropdownOpen, setDropdownOpen] = useState(false);
const [commentCount, setCommentCount] = useState(0);
const [isLoaded, setIsLoaded] = useState(false);

useEffect(() => {
const fetchPost = async () => {
const postDoc = await getDoc(doc(db, 'Forum', postID));
const fetchData = async () => {
if (isLoaded) return;

if (postDoc.exists()) {
const postData = postDoc.data();
setPost(postData);
try {
const postDoc = await getDoc(doc(db, 'Forum', postID));

const userDocRef = doc(db, 'Users', postData.userID);
const userDocSnap = await getDoc(userDocRef);
if (userDocSnap.exists()) {
setUser(userDocSnap.data());
}
} else {
console.log('There is no such post');
}
}
if (postDoc.exists()) {
const postData = postDoc.data();
setPost(postData);

const fetchComments = async () => {
const commentsData = await fetchCommentsRecursively(postID);
setComments(commentsData);
};
const userDocRef = doc(db, 'Users', postData.userID);
const userDocSnap = await getDoc(userDocRef);
if (userDocSnap.exists()) {
setUser(userDocSnap.data());
}

const checkIfLiked = async () => {
if (currentUser) {
const likesQuery = query(
collection(db, 'Forum', postID, 'Likes'),
where('userID', '==', currentUser.uid)
);
const likesSnapshot = await getDocs(likesQuery);
if (!likesSnapshot.empty) {
setIsLiked(true);
}
}
};
const commentsData = await fetchCommentsRecursively(postID);
setComments(commentsData);

const getLikeCount = async () => {
const likesSnapshot = await getDocs(collection(db, 'Forum', postID, 'Likes'));
setLikeCount(likesSnapshot.size);
};
if (currentUser) {
const likesQuery = query(
collection(db, 'Forum', postID, 'Likes'),
where('userID', '==', currentUser.uid)
);
const likesSnapshot = await getDocs(likesQuery);
setIsLiked(!likesSnapshot.empty);
}

const likesSnapshot = await getDocs(collection(db, 'Forum', postID, 'Likes'));
setLikeCount(likesSnapshot.size);

if (currentUser && postData.poll && postData.poll.votes) {
const hasVoted = Object.values(postData.poll.votes).some(
voters => voters.includes(currentUser.uid)
);
if (hasVoted) {
setShowResults(true);
setSelectedPollOption(
Object.entries(postData.poll.votes).find(
([, voters]) => voters.includes(currentUser.uid)
)?.[0]
);
}
}

fetchPost();
checkIfLiked();
getLikeCount();
fetchComments();

if (currentUser && post) {
if (currentUser.uid === post.userID) {
setShowResults(true);
} else if (post.poll && post.poll.votes) {
const hasVoted = Object.values(post.poll.votes).some(
voters => voters.includes(currentUser.uid)
);
if (hasVoted) {
setShowResults(true);
setSelectedPollOption(
Object.entries(post.poll.votes).find(
([, voters]) => voters.includes(currentUser.uid)
)?.[0]
);
setIsLoaded(true);
} else {
console.log('There is no such post');
}
} catch (error) {
console.error("Error fetching data:", error);
}
}
}, [postID, currentUser, post]);
};

fetchData();
}, [postID, currentUser, isLoaded]);

const countCommentsAndReplies = (comments) => {
return comments.reduce((total, comment) => {
Expand All @@ -211,7 +205,7 @@ function ForumPostPage() {
const commentData = {
content: commentContent,
userId: currentUser.uid,
timestamp: new Date()
timestamp: new Date().toISOString()
};

try {
Expand Down Expand Up @@ -240,7 +234,7 @@ function ForumPostPage() {
listingID: postID,
type: 'forum-comment',
read: false,
timestamp: new Date()
timestamp: new Date().toISOString()
});
}

Expand Down

0 comments on commit 8284269

Please sign in to comment.