Home > OS >  how to implement infinite scroll nextjs
how to implement infinite scroll nextjs

Time:06-16

I am new in reactjs. I found few question on this topics on stackoverflow and also search google but still now I can't implement infinite scroll. I am struggling from almost yesterday for implementing infinite scroll.

I used django rest for building my api. Here is my api call look like: my api url : http://127.0.0.1:8000/blog-api/?limit=2

{
    "count": 6, 
    "next": "http://127.0.0.1:8000/blog-api/?limit=2&offset=2",
    "previous": null,
    "results": [
        {
            "id": 4,
            "blog_title": "Blog1",
            "blog_body": "hello",
            "blog_header_image": "https://d2ofoaxmq8b811.cloudfront.net/media/Capture_46syzro.PNG",
            "author": 1
        },
        {
            "id": 5,
            "blog_title": "blog2",
            "blog_body": "hello2",
            "blog_header_image": "https://d2ofoaxmq8b811.cloudfront.net/media/Capture1.PNG",
            "author": 4
        }
    ]
}

here is my nextjs code which currently displaying 2 items in my page but I also want to get load more data on scrolling:

const Blog = ({ content }) => {
  return (
     {content.results.map((data) => (
           <h1>{data.blog_title}</h1>   
     ))}
 
)}     

Here I am using getServerSideProps function.

export async function getServerSideProps() {
  // Fetch data from external API
  const url = "http://127.0.0.1:8000/blog-api?limit=2";
  const headers = {
    method: "GET",
    "Content-Type": "application/json",
    Accept: "application/json",
    "User-Agent": "*",
    Authorization: "Token <>",
  };
  const res = await fetch(url, { headers: headers });

  const data = await res.json();

  console.log(data);
  // Pass data to the page via props
  return {
    props: {
      content: data,
    },
  };
}

I also tried react-infinite-scroll-component and also read their documentation but can't apply infinite-scroll.

CodePudding user response:

You can use useSWR example, as you already have an API

CodePudding user response:

you can create hooks that check if the component is in the viewport. after that create an event that will be triggered when that component is visible

const useInViewport = (element, rootMargin) => {
    const [isVisible, setState] = useState(false);

    useEffect(() => {
        const observer = new IntersectionObserver(
            ([entry]) => {
                setState(entry.isIntersecting);
            }, { rootMargin }
        );

        element.current && observer.observe(element.current);

        return () => observer.unobserve(element.current);
    }, []);

    return isVisible;
};

Use the useInviewport hook:

const YourComponent = () => {
    const ref = useRef();
    const inViewport = useInViewport(ref, '0px'); // Trigger as soon as the element becomes visible

    if (inViewport) {
        console.log('in viewport:', ref.current);
        //DO YOUR API CALL HERE
    }

    return (
        <React.Fragment>
            <Header />
            <YourContentContent />
            <Footer ref={ref} />
        </React.Fragment>
    );
}
  • Related