1- import { useState , useEffect } from "react" ;
1+ import { useState , useEffect , useCallback } from "react" ;
22import { Post } from "../types/post" ;
33import { getExcerpt } from "../utils/excerpt" ;
44import 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