MCPcopy Create free account
hub / github.com/SuboptimalEng/coding-tutorials / Home

Function Home

react-infinite-scroller/pages/index.jsx:5–68  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

3import { useEffect, useState } from "react";
4
5export default function Home() {
6 let currentOffset = 0;
7 const [pokemon, setPokemon] = useState([]);
8
9 const loadTenPokemon = () => {
10 const tenPokemon = [];
11 axios
12 .get(`https://pokeapi.co/api/v2/pokemon?limit=10&offset=${currentOffset}`)
13 .then(({ data }) => {
14 data.results.forEach((p) => tenPokemon.push(p.name));
15 setPokemon((pokemon) => [...pokemon, ...tenPokemon]);
16 });
17 currentOffset += 10;
18 };
19
20 const handleScroll = (e) => {
21 console.log(e.target.documentElement.scrollTop);
22 console.log(window.innerHeight);
23 console.log(e.target.documentElement.scrollHeight);
24 // console.log(
25 // Math.ceil(e.target.documentElement.scrollTop + window.innerHeight)
26 // );
27 const scrollHeight = e.target.documentElement.scrollHeight;
28 const currentHeight = Math.ceil(
29 e.target.documentElement.scrollTop + window.innerHeight
30 );
31 if (currentHeight + 1 >= scrollHeight) {
32 loadTenPokemon();
33 }
34 };
35
36 useEffect(() => {
37 loadTenPokemon();
38 window.addEventListener("scroll", handleScroll);
39 }, []);
40
41 return (
42 <div
43 className="flex
44 flex-col items-center
45 justify-center min-h-screen py-2
46 bg-gray-900 text-gray-200"
47 >
48 <Head>
49 <title>Create Next App</title>
50 <link rel="icon" href="/favicon.ico" />
51 </Head>
52
53 <div className="flex flex-col text-4xl font-bold items-center justify-center w-full px-20 text-center">
54 {pokemon.map((p, i) => {
55 return (
56 <div
57 key={i}
58 className="border w-80 h-40 flex justify-around place-items-center"
59 >
60 <div>{i + 1}.</div>
61 <div>{p}</div>
62 </div>

Callers

nothing calls this directly

Calls 1

loadTenPokemonFunction · 0.85

Tested by

no test coverage detected