Skip to content

Commit 62f940b

Browse files
committed
Bug: Fix Load More button
Signed-off-by: Kevin Wong <[email protected]>
1 parent 20ecf64 commit 62f940b

File tree

1 file changed

+21
-4
lines changed

1 file changed

+21
-4
lines changed

components/more-stories.tsx

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useState, useEffect } from "react";
1+
import { useState, useEffect, useCallback } from "react";
22
import { Post } from "../types/post";
33
import { getExcerpt } from "../utils/excerpt";
44
import PostPreview from "./post-preview";
@@ -54,7 +54,7 @@ export default function MoreStories({
5454
};
5555

5656
// Fetch more posts in background
57-
const loadMoreInBackground = async () => {
57+
const loadMoreInBackground = useCallback(async () => {
5858
try {
5959
const category = isCommunity ? 'community' : 'technology';
6060
const result = await fetchMorePosts(category, endCursor);
@@ -70,8 +70,25 @@ export default function MoreStories({
7070
console.error('Error fetching more posts:', error);
7171
setError('Failed to load more posts. Please try again later.');
7272
}
73-
};
73+
}, [isCommunity, endCursor]);
74+
7475

76+
useEffect(() => {
77+
if (!isIndex) return;
78+
79+
const onScroll = () => {
80+
const threshold = 500;
81+
if (
82+
window.innerHeight + window.scrollY >= document.body.offsetHeight - threshold
83+
&& !loading &&
84+
hasMore ) {
85+
loadMoreInBackground();
86+
}
87+
}
88+
window.addEventListener("scroll", onScroll)
89+
return () => window.removeEventListener("scroll", onScroll)
90+
}, [loading, hasMore, loadMoreInBackground])
91+
7592
const loadMorePosts = async () => {
7693
if (loading) return;
7794

@@ -121,7 +138,7 @@ export default function MoreStories({
121138
visibleCount < allPosts.length ||
122139
buffer.length > 0 ||
123140
hasMore
124-
) && !loading && !error && isIndex;
141+
) && !error && isIndex;
125142

126143
return (
127144
<section>

0 commit comments

Comments
 (0)