import React, { useState, useEffect, useRef } from "react"; import Post from "../Post"; import "./feed.css"; function Feed() { const [posts, setPosts] = useState([]); const [loading, setLoading] = useState(false); const [hasMore, setHasMore] = useState(true); const feedRef = useRef(null); const PAGE_SIZE = 10; // Dummy fetch function that simulates loading posts by ID const fetchPosts = () => { if (loading) return; setLoading(true); setTimeout(() => { setPosts((prev) => { const newPosts = []; for (let i = 0; i < PAGE_SIZE; i++) { newPosts.push(prev.length + i + 1); } return [...prev, ...newPosts]; }); setLoading(false); // Stop after 50 posts, just as an example if (posts.length + PAGE_SIZE >= 50) { setHasMore(false); } }, 800); }; useEffect(() => { fetchPosts(); }, []); useEffect(() => { const onScroll = () => { const feed = feedRef.current; if (!feed || loading || !hasMore) return; if (feed.scrollTop + feed.clientHeight >= feed.scrollHeight - 100) { fetchPosts(); } }; const feed = feedRef.current; feed?.addEventListener("scroll", onScroll); return () => { feed?.removeEventListener("scroll", onScroll); }; }, [loading, hasMore]); return (
{posts.map((postId) => ( ))} {loading &&
Loading more posts...
} {!hasMore &&
No more posts
}
); } export default Feed;