import { addDoc, collection, deleteDoc, doc, onSnapshot, orderBy, query, serverTimestamp, setDoc, } from "firebase/firestore"; import { motion } from "framer-motion"; import moment from "moment"; import { useSession } from "next-auth/react"; import { useRouter } from "next/router"; import React, { useEffect, useState } from "react"; import { firestore } from "../firebase/firebase"; type PostProps = { id: string; username: string; userImage: string; img: string; caption: string; userId: string; }; const Post: React.FC = ({ id, username, userImage, img, caption, userId, }) => { const { data: session } = useSession(); const router = useRouter(); const [comment, setComment] = useState(""); const [comments, setComments] = useState([]); const [likes, setLikes] = useState([]); const [hasLikes, setHasLikes] = useState(false); const [loading, setLoading] = useState(false); const sendComment = async (e: any) => { e.preventDefault(); if (comment) { setLoading(true); try { await addDoc(collection(firestore, "posts", id, "comments"), { comment: comment, username: session?.user?.name, userImage: session?.user?.image, timestamp: serverTimestamp(), }); setLoading(false); } catch (error) { console.log(error); } setComment(""); } else { console.log("err"); } }; useEffect( () => onSnapshot( query( collection(firestore, "posts", id, "comments"), orderBy("timestamp", "desc") ), (snapshot) => setComments(snapshot.docs) ), [firestore, id] ); useEffect( () => onSnapshot(collection(firestore, "posts", id, "likes"), (snapshot) => setLikes(snapshot.docs) ), [firestore, id] ); useEffect( () => setHasLikes( likes.findIndex((like) => like.id === session?.user?.uid) !== -1 ), [likes] ); const likePost = async () => { try { if (hasLikes) { await deleteDoc( doc(firestore, "posts", id, "likes", session?.user?.uid!) ); } else { await setDoc( doc(firestore, "posts", id, "likes", session?.user?.uid!), { username: session?.user?.name, } ); } } catch (error) { console.log(error); } }; const handleChangePage = () => { if (session) { router.push({ pathname: `profile/${userId}`, query: { userId: userId.toString(), }, }); } else { router.push("/auth/login"); } }; return (

{username}

{session && (
{hasLikes ? ( ) : ( )}
)}

{likes.length > 0 && (

{likes.length} likes

)} {username} {caption}

{/* comments */} {comments.length > 0 && (
{comments.map((comment) => (

{comment.data().username} {comment.data().comment}

{moment( new Date(comment.data().timestamp?.seconds * 1000) ).fromNow()}

))}
)} {session && (
setComment(e.target.value)} placeholder="Add a comment..." className="border-none flex-1 focus:ring-0 outline-none" /> {loading ? ( ) : ( Post )}
)}
); }; export default Post;