버튼을 클릭하면 로드하던 방식에서,
무한 스크롤링 방식으로 변경해보자.
component > product-list.tsx
// ...
import { useRef, useState } from "react";
// ...
export default function ProductList( {initialProducts}: ProductListProps) {
// ...
const trigger = useRef<HTMLSpanElement>(null);
const onLoadMoreClick = async() => {
setIsLoading(true);
const newProducts = await getMoreProducts(page+1); // 받고
if(newProducts.length !== 0) { // 새상품이 더 있을 때에만
setPage((prev) => prev + 1);
setProducts(prev => [...prev, ...newProducts]); // 머지 (모두 array로 받기 때문에 ...로 펼침)
} else {
setIsLastPage(true);
}
setIsLoading(false)
}
return (
<div className="p-5 flex flex-col gap-5">
{products.map((product) => (
<ListProduct key={product.id} {...product} />
))}
{/* 무한 스크롤링으로 변경 */}
<span
ref={trigger}
className="mt-[300vh] mb-96 text-sm font-semibold bg-orange-500 w-fit mx-auto px-3 py-2 rounded-md hover:opacity-90 active:scale-95">
{isLoading ? "로딩 중" : "Load more"}
</span>
</div>
)
}