import React, { useEffect, useState } from "react"; import { useInView } from "react-intersection-observer"; import "./App.css"; const getApiUrl = (page: number, limit: number) => { console.log("page", page); return `https://picsum.photos/v2/list?page=${page}&limit=${limit}`; }; export interface ImageItem { id: string; author: string; width: number; height: number; url: string; download_url: string; } const LIMIT = 5; const fetchImages = async (page: number) => { const res = await fetch(getApiUrl(page, LIMIT)); const data = await res.json(); return data; }; function App() { const [page, setPage] = useState(0); const [images, setImages] = useState([] as ImageItem[]); const { ref, inView } = useInView({ initialInView: false, }); useEffect(() => { if (inView && images.length > 0) { setPage((prev) => prev + 1); } }, [inView]); // on mount useEffect(() => { const fetchInitialData = async () => { // console.log(page); const imgs = await fetchImages(page); // console.log(imgs.map((i: any) => i.id)); const newState = [...images, ...imgs]; console.log({ newState }); setImages(newState); }; fetchInitialData(); }, [page]); return (
{images.map((item) => { return ; })}
); } export default App;