nori-dongsan / nori-client

💚nori-dongsan💚 Client의 퍼레이드로 여러분을 초대합니다 🥳🥳🥳🥳
https://www.with-nori.com/
6 stars 2 forks source link

[ Collection Product ] 페이지네이션 라이브러리 만들기 #52

Closed Happhee closed 2 years ago

Happhee commented 2 years ago

🔥 Related Issues

🎡 작업 내용

✅ PR Point

pages/collectionProduct

const limit = 40;
export default function collectionProduct() {
  const { query } = useRouter();
  const { collection } = query;
  const [toyList, setToyList] = useState<ToyData[]>([]);
  const [currentPage, setCurrentPage] = useState<number>(1);

  const handleCurrentPage = (nextPage: number) => {
    setCurrentPage(nextPage);
  };
// ✅ 일단 상품리스트 다 가져오기 
  let { productList, isLoading, isError } = useGetCollectionProduct(
    'price-desc',
  ) as GetCollectionProduct;

  useEffect(() => {
    if (productList) {
      let data = productList as ToyData[];
      data = data.filter(
// ✅ 현재 페이지에 맞는 데이터만 남겨두기
        (_, idx) => (currentPage - 1) * 40 <= idx && idx < currentPage * 40,
      );
      setToyList(data);
// ✅ 페이지 맨위로 올라가게 !! 리렌더링과 동시
      window.scrollTo(0, 0);
    }
  }, [productList, currentPage]);

  return (
    <StCollectionSection>
      <StCollectionTitle>{collection}</StCollectionTitle>
      <PriceFilter />
      <StToyListWrapper>
        {toyList.map(
          (_, idx) =>
// ✅ 4개씩 보여주기 위한 조건문
            (idx + 1) % 4 === 0 && (
              <CollectionList
                key={idx}
// ✅ slice 메서드 사용하여 전달 
                toyList={toyList.slice(idx - 3, idx + 1)}
              />
            ),
        )}
      </StToyListWrapper>
      {!isLoading && !isError && (
        <PageNavigation
          currentPage={currentPage}
          lastPage={Math.ceil(productList.length / limit)}
          handleCurrentPage={handleCurrentPage}
        />
      )}
    </StCollectionSection>
  );
}

👀 스크린샷 / GIF / 링크

ezgif com-gif-maker (22)

📚 Reference

-서히 SOPT 8주차 개인공부