choigirang / why-chat

아왜진 커뮤니티 미니 프로젝트
https://fe.why-chat.site
0 stars 0 forks source link

작성한 글, 댓글, 좋아요 등 조회 #17

Open choigirang opened 1 year ago

choigirang commented 9 months ago

BE

export async function userAllData(req: Request, res: Response) {
  const { id } = req.query;

  try {
    const userInfo = await User.findOne({ id });
    const userPosts = await Post.find({ author: id });

    const userAllComments: CommentData[] = [];

    // 유저가 작성한 댓글 데이터
    const allPosts = await Post.find();

    allPosts.forEach(post => {
      post.comments.forEach(comment => {
        if (comment.author === id) {
          userAllComments.unshift({
            title: post.title,
            postNumber: post.postNumber,
            author: post.author,
            comment: comment.comment,
            date: comment.date,
          });
        }
      });
    });

    return res.status(200).send({ userPosts, userAllComments, userInfo });
  } catch (err) {
    return res.status(404).send(err);
  }
}
choigirang commented 9 months ago

FE

export default function UserData({ data }: { data: UserDataLogType }) {
  // 페이지당 보여질 갯수
  const [perPage, setPerPage] = useState(5);

  // 페이지
  const [postCurtPage, setPostCurtPage] = useState(1);
  const [postPageCount, setPostPageCount] = useState(0);

  const [commentCurtPage, setCommentCurtPage] = useState(1);
  const [commentPageCount, setCommentPageCount] = useState(0);

  const [likesCurtPage, setLikesCurtPage] = useState(1);
  const [likesPageCount, setLikesPageCount] = useState(0);

  const { userInfo } = data;
  // 작성한 게시글
  const postsData = data.userPosts;
  // 작성한 댓글
  const commentsData = data.userAllComments;
  // 좋아요 누른
  const likes = userInfo.likes;

  useEffect(() => {
    if (postsData) {
      const pageCount = Math.ceil(postsData.length / perPage);
      setPostPageCount(pageCount);
    }

    if (commentsData) {
      const pageCount = Math.ceil(commentsData.length / perPage);
      setCommentPageCount(pageCount);
    }

    if (likes) {
      const pageCount = Math.ceil(likes.length / perPage);
      setLikesPageCount(pageCount);
    }
  }, [postsData, perPage]);

  // 현재 페이지의 게시글 가져오기
  const getCurrentPagePosts = () => {
    if (postsData) {
      const startIndex = (postCurtPage - 1) * perPage;
      const endIndex = startIndex + perPage;
      return postsData.slice(startIndex, endIndex);
    }
    return [];
  };

  // 현재 페이지의 댓글 가져오기
  const getCurrentPageComments = () => {
    if (commentsData) {
      const startIndx = (commentCurtPage - 1) * perPage;
      const endIndx = startIndx + perPage;
      return commentsData.slice(startIndx, endIndx);
    }

    return [];
  };

  // 현재 페이지의 좋아요 가져오기
  const getCurrentPageLikes = () => {
    if (likes) {
      const startIndex = (likesCurtPage - 1) * perPage;
      const endIndex = startIndex + perPage;
      return likes.slice(startIndex, endIndex);
    }

    return [];
  };

  // 각 섹션의 페이지네이션 처리 함수
  const handlePostPageCount = (selectedItem: { selected: number }) => {
    setPostCurtPage(selectedItem.selected + 1);
  };

  const handleCommentPageCount = (selectedItem: { selected: number }) => {
    setCommentCurtPage(selectedItem.selected + 1);
  };

  const handleLikesPageCount = (selectedItem: { selected: number }) => {
    setLikesCurtPage(selectedItem.selected + 1);
  };
  return (
    <Container>
      <List>
        {/* 게시글 */}
        <p className="sub-title">내가 작성한 글</p>
        {getCurrentPagePosts().map(post => (
          <UserPostData key={post.postNumber} post={post} />
        ))}
        <Pagination pageCount={postPageCount} onPageChange={handlePostPageCount} />
      </List>
      <List>
        {/* 댓글 */}
        <p className="sub-title">내가 작성한 댓글</p>
        {getCurrentPageComments().map((comment, idx) => (
          <UserCommentData key={idx} {...comment}></UserCommentData>
        ))}
        <Pagination pageCount={commentPageCount} onPageChange={handleCommentPageCount} />
      </List>
      <List>
        {/* 좋아요 */}
        <p className="sub-title">좋아요 누른 글</p>
        {getCurrentPageLikes().map((like, idx) => (
          <UserLikes key={idx} {...like}></UserLikes>
        ))}
        <Pagination pageCount={likesPageCount} onPageChange={handleLikesPageCount} />
      </List>
    </Container>
  );
}
export default function UserPostData({ post }: { post: PostType }) {
  // 카테고리 추가

  const viewContainerRef = React.useRef<HTMLDivElement>(null);

  // useEffect
  useEffect(() => {
    if (viewContainerRef.current) {
      viewContainerRef.current.innerHTML += post.body;
    }
  }, [post.body]);

  return (
    <Container>
      <Linked href={`/community/post/${post.postNumber}`}>
        <Top>
          <p className="title">{post.title}</p>
          <p className="date">{post.date}</p>
        </Top>
        <div className="body" ref={viewContainerRef} />
      </Linked>
    </Container>
  );
}
interface PaginationProps {
  pageCount: number;
  onPageChange: (selectedItem: { selected: number }) => void;
  initialPageCount?: number; // 새로운 prop 추가
}

const Pagination = ({ pageCount, onPageChange }: PaginationProps) => {
  return (
    <Container>
      <ReactPaginate
        pageCount={pageCount}
        previousLabel={<AiFillCaretLeft />}
        nextLabel={<AiFillCaretRight />}
        pageRangeDisplayed={5} // 보여질 페이지 수
        marginPagesDisplayed={1} // 페이지네이션 컴포넌트의 좌우 여백 페이지 수
        onPageChange={onPageChange}
        containerClassName="pagination"
        activeClassName="active"
        renderOnZeroPageCount={null}
      />
    </Container>
  );
};