#How to implement InfiniteScroll in

1 messages · Page 1 of 1 (latest)

lapis tartan
spiral jasperBOT
#

Hi @lapis tartan. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Sorry @lapis tartan, I seem to be having a bit of trouble. Don't worry though, I've pinged my supprt and they will try to fix me up! :technologist:

Perhaps try again in 15mins?

lapis tartan
#

Here's the code I am trying

#
import { useState, useEffect } from 'react';
import InfiniteScroll from 'react-infinite-scroll-component';
import ContentSection from '@/components/ContentSection';

function Papers() {
  const [posts, setPosts] = useState([]);
  const [page, setPage] = useState(0);
  const [hasMore, setHasMore] = useState(true);

  const fetchPosts = async () => {
    try {
      const res = await fetch(`/api/getLatestData?page=${page}`);
      const data = await res.json();

      if (data.length === 0) {
        setHasMore(false);
        return;
      }

      setPosts([...data]);
      setPage(page + 1);
    } catch (error) {
      console.error(error);
    }
  };

  useEffect(() => {
    fetchPosts();
  }, []);

  return (
<div>
        <InfiniteScroll
          dataLength={posts.length}
          next={fetchPosts}
          hasMore={hasMore}
          loader={<h4 className="my-8 text-center">Loading...</h4>}
        >
          {posts.map(post => (
            <ContentSection key={post.createdAt} title={post.title} content={post.content} />
          ))}
        </InfiniteScroll>
      </div>
  );
}

export default Papers;
#

The trouble is that /api/getLatestData is to be run on server side because it contain some api keys.

#

And with 'use client' I can't use it, without NEXT_PUBLIC_ with isn't the right way

lapis tartan
#

Hey @broken rover
Sorry for ping, but spent a lot of time on this. Can you give me any direction to refactor this or some other example to understand