how to create load more bottom in nextjs for get rest of data? (Next.js Pagination)

Viewed 5270

I want to click on Load More bottom and get the rest of data in next.js how can do this? in this page I'm using getServerSideProps to get data from api

My Page code is :

export default function Posts({ posts, popular }) {
  const classes = useStyles();
  return (
    <motion.main
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
    >
      <InnerWrapper pbNone>
        <Title title="Latest Post" subTitle />
      </InnerWrapper>
      <HeroSection data={posts} />
      <InnerWrapper>
        <Grid container spacing={3}>
          <Grid item xs={12} sm={8}>
            {posts.map(item => (
              <HorizontalCard key={item.id} info={item} />
            ))}

            <LoadMoreBtn />
            
          </Grid>
          <Grid item xs={12} sm={4}>
            <div className={classes.marginBottom}>
              <Title title={"Most Popular"} subTitle side={true} />
              <SideList data={popular} />
            </div>
            <div className={classes.marginBottom}>
              <SubscribeSide />
            </div>
          </Grid>
        </Grid>
      </InnerWrapper>
    </motion.main>
  );
}

export const getServerSideProps = async ({ query }) => {
  // Fetch data from external API
  const { data: posts } = await postLists(0);
  const { data: popular } = await popularPost();
  // Pass data to the page via props
  return { props: { posts, popular } };
};
1 Answers

getServerSideProps is for getting data to be used for the first render. Unlike that, your "load more" button needs to work on the client-side.

I will try to summarize the steps you should take:

  1. In order to be able to manipulate the posts that will be displayed, you need to store your items in the state, not props. So, create a state using useState and fill it with the data coming from the props, something like this:

    const [posts, setPosts] = useState(props.posts);
    

    From now on, you will use this posts variable instead of the one from the props.

  2. Add the "load more" button. All loading more posts business logic should go to its onClick handler. Something like this:

    <button
      onClick={async () => {
         const newPosts = await getNewPostsFromApi();
    
         setPosts(...posts, ...newPosts);
      }}
      type="button"
    >
    Load more
    </button>
    
Related