Last active
March 6, 2024 15:27
-
-
Save ajeetkumarrauniyar/1014ddcdefb22bebfe86975b53ade06e to your computer and use it in GitHub Desktop.
Infinite Scroll for Blog Posts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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