DEV Community

MOHSIN ALI SOOMRO
MOHSIN ALI SOOMRO

Posted on

infinity scroll down reactjs

Code

import { useCallback, useEffect, useState } from "react";
import "./styles.css";
import InfiniteScroll from "react-infinite-scroll-component";
export default function App() {
  const [state, setState] = useState([]);
  const [data, setData] = useState([]);
  const [hasMore, setHasMore] = useState(true);
  const [perPage] = useState(20);
  const [currentPage, setCurrentPage] = useState(1);
  const lastIndex = currentPage * perPage;
  const firstIndex = lastIndex - perPage;

  const fetchPost = async () => {
    const json = await fetch("https://jsonplaceholder.typicode.com/posts");
    const result = await json.json();
    setState(result);
  };

  const fetchMore = useCallback(() => {
    setTimeout(() => {
      setCurrentPage(currentPage + 1);
      let d = [...state].slice(firstIndex, lastIndex);
      setData((prev) => [...prev, ...d]);
    }, 1000);
  },[state])

  useEffect(() => {
    fetchPost();
    if (state.length) fetchMore();
  }, []);

  useEffect(() => {
    if (data.length < state.length) {
      setHasMore(true);
    } else {
      setHasMore(false);
    }
  }, [state]);
  console.log({ state, data, lastIndex, firstIndex, currentPage });
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>

      <InfiniteScroll
        dataLength={data.length}
        next={fetchMore}
        hasMore={hasMore}
        loader={<h4>Loading...</h4>}
        scrollableTarget="scrollableDiv"
      >
        {data.length &&
          data.map((post) => {
            return (
              <div
                style={{
                  backgroundColor: "green ",
                  padding: "10px",
                  margin: "10px"
                }}
              >
                {post.title}
              </div>
            );
          })}
      </InfiniteScroll>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Discussion (0)