I would like to make an infinite scroll with Intersection Observer that in the call back function increments the page number from an API and displays another image.
I am stuck on how I can call the API again and increment the page.
This is what I tried:
const [page, setPage] = useState(1);
const [images, setImages] = useState(null);
const lastItem = useRef(null);
useEffect(() => {
const intersection = new IntersectionObserver(() => {
// setPage(page + 1);
});
if (lastItem.current) {
intersection.observe(lastItem.current);
}
});
useEffect(() => {
async function dataSet() {
const data = await fetch(`https://api.themoviedb.org/3/trending/movie/week?api_key=${apiKey}&page=${page}`).then((res) => res.json());
setImages(data);
}
dataSet();
}, [apiKey, page]);
useEffect(() => {});
if (!images) {
return <h2>Loading...</h2>;
}
return (
<>
<Nav />
<main>
<section className={styles.spacer}>
<h1>Trending Movies</h1>
<ul className={styles.grid}>
{images.results?.map((image) => {
return (
<li className={styles.gridItem} key={image.id} ref={lastItem}>
<img src={`https://image.tmdb.org/t/p/w370_and_h556_bestv2/${image.poster_path}`} alt={image.name} />
<p className={styles.title}>{image.original_title}</p>
</li>
);
})}
</ul>
</section>
</main>
<Footer />
</>
);
}