Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 21 additions & 4 deletions components/more-stories.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useState, useEffect } from "react";
import { useState, useEffect, useCallback } from "react";
import { Post } from "../types/post";
import { getExcerpt } from "../utils/excerpt";
import PostCard from "./post-card";
Expand Down Expand Up @@ -55,7 +55,7 @@ export default function MoreStories({
};

// Fetch more posts in background
const loadMoreInBackground = async () => {
const loadMoreInBackground = useCallback(async () => {
try {
const category = isCommunity ? 'community' : 'technology';
const result = await fetchMorePosts(category, endCursor);
Expand All @@ -71,8 +71,25 @@ export default function MoreStories({
console.error('Error fetching more posts:', error);
setError('Failed to load more posts. Please try again later.');
}
};
}, [isCommunity, endCursor]);


useEffect(() => {
if (!isIndex) return;

const onScroll = () => {
const threshold = 500;
if (
window.innerHeight + window.scrollY >= document.body.offsetHeight - threshold
&& !loading &&
hasMore ) {
loadMoreInBackground();
}
}
window.addEventListener("scroll", onScroll)
return () => window.removeEventListener("scroll", onScroll)
}, [loading, hasMore, loadMoreInBackground])

const loadMorePosts = async () => {
if (loading) return;

Expand Down Expand Up @@ -122,7 +139,7 @@ export default function MoreStories({
visibleCount < allPosts.length ||
buffer.length > 0 ||
hasMore
) && !loading && !error && isIndex;
) && !error && isIndex;

return (
<section>
Expand Down