Skip to content

Instantly share code, notes, and snippets.

@ajeetkumarrauniyar
Last active March 6, 2024 15:27
Show Gist options
  • Save ajeetkumarrauniyar/1014ddcdefb22bebfe86975b53ade06e to your computer and use it in GitHub Desktop.
Save ajeetkumarrauniyar/1014ddcdefb22bebfe86975b53ade06e to your computer and use it in GitHub Desktop.
Infinite Scroll for Blog Posts
import React, { useState, useEffect } from 'react';
const PostList = () => {
const [posts, setPosts] = useState([]);
const [currentPage, setCurrentPage] = useState(1);
const [hasMorePosts, setHasMorePosts] = useState(true);
useEffect(() => {
fetchInitialPosts();
}, []);
const fetchInitialPosts = async () => {
// ... Fetch posts for page 1 and update state
};
const fetchMorePosts = async () => {
// ... Update currentPage, fetch posts for the new page, and update state
};
const handleScroll = () => {
if (window.innerHeight + window.scrollY >= document.body.offsetHeight && hasMorePosts) {
fetchMorePosts();
}
};
useEffect(() => {
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, []);
return (
<div>
{posts.map((post) => (
<Post key={post.id} {...post} />
))}
{hasMorePosts && <p>Loading more posts...</p>}
</div>
);
};
export default PostList;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment