2024.04.07 TIL - 최종프로젝트 13일차(최신순, 좋아요순 정렬)

Innes·2024년 4월 7일
0

TIL(Today I Learned)

목록 보기
109/127
post-thumbnail

커뮤니티 리스트 최신순, 좋아요순 정렬

  1. 기존 api 수정 - 외래키로 연결된 likes 테이블의 post_id 가져오는 로직 추가하기
// 커뮤니티 리스트 가져오기 - 작성자 정보, 좋아요도 함께
export const getCommunityList = async () => {
  const { data: communityList, error } = await supabase
    .from("community_posts")
    .select(`*, users(display_name, profile_img), likes(post_id)`);

  if (error) {
    console.log("error", error);
    throw error;
  }

  return communityList;
};
  1. useQuery로 가져온 communityList를 가지고 정렬 구성하기
// ⭐️ useQuery로 communityList 가져오기
 const {
    data: communityList,
    isLoading,
    isError,
  } = useQuery({
    queryKey: [QUERY_KEY_COMMUNITYLIST],
    queryFn: getCommunityList,
  });


// ⭐️ 가져온 communityList를 최신순 정렬하기
    // (new Date()를 사용하여 날짜를 비교할 때에는 각 날짜를 밀리초 단위로 변환해야 함 
    // -> .getTime() 사용)
  const sortedLatestCommunityList = communityList?.slice().sort((a, b) => {
    return new Date(b.created_at).getTime() - new Date(a.created_at).getTime();
  });


// ⭐️ communityList 좋아요순 정렬
    // 각 게시물의 좋아요 개수 계산 - communityList의 key에 likes_count를 추가하기
  const communityListWithLikesCount = communityList?.map((post) => {
    return {
      ...post,
      likes_count: post.likes.length,
    };
  });

  // 좋아요 개수(likes_count)를 기준으로 정렬
  const sortedLikesCommunityList = communityListWithLikesCount?.sort(
    (a, b) => b.likes_count - a.likes_count,
  );
  1. 페이지 렌더링시 + '최신순' 클릭시 - sortedLatestCommunityList를 map,
    '좋아요순' 클릭시 - sortedLikesCommunityList를 map
  // 정렬 드랍다운 상태
  const [selectedKeys, setSelectedKeys] = React.useState<Selection>(
    new Set(["정렬"]),
  );

  // 드랍다운 선택값 추출 로직
  const selectedValue = React.useMemo(
    () => Array.from(selectedKeys).join(", ").replaceAll("_", " "),
    [selectedKeys],
  );

    //(...생략)

{/* 커뮤니티 게시글 카드 map */}
          {selectedValue === "정렬" || selectedValue === "최신순(기본)"
            ? sortedLatestCommunityList?.map((communityPost) => (
                <CommunityListPost
                  key={communityPost.id}
                  communityPost={communityPost}
                  mode="community"
                />
              ))
            : sortedLikesCommunityList?.map((communityPost) => (
                <CommunityListPost
                  key={communityPost.id}
                  communityPost={communityPost}
                  mode="community"
                />
              ))}
profile
꾸준히 성장하는 우상향 개발자

0개의 댓글