Created
September 22, 2023 21:09
-
-
Save olegakbarov/f2e88750d108c2c5bcdc5f48b7b60130 to your computer and use it in GitHub Desktop.
Revisions
-
olegakbarov created this gist
Sep 22, 2023 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,66 @@ 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<ImageItem[]>([] 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 ( <div className="App"> {images.map((item) => { return <img key={item.id} src={item.download_url} />; })} <div ref={ref} /> </div> ); } export default App;