DEV Community

MOHSIN ALI SOOMRO
MOHSIN ALI SOOMRO

Posted on

3

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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay