Skip to content
Merged
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
11 changes: 3 additions & 8 deletions hooks/use-infinite-scroll.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,14 @@ export function useInfiniteScroll<T>({
useEffect(() => {
if (!inView || loading || !hasMore) return;

let cancelled = false;
const currentPage = pageRef.current;
const generation = ++fetchGenRef.current;

setLoading(true);

fetchMoreRef.current(currentPage)
.then(({ data: newData, hasMore: newHasMore }) => {
if (cancelled || fetchGenRef.current !== generation) return;
if (fetchGenRef.current !== generation) return;

if (newData.length > 0) {
setData((prev) => [...prev, ...newData]);
Expand All @@ -47,18 +46,14 @@ export function useInfiniteScroll<T>({
setHasMore(newHasMore && newData.length > 0);
})
.catch((error) => {
if (cancelled || fetchGenRef.current !== generation) return;
if (fetchGenRef.current !== generation) return;
console.error("Error fetching more data:", error);
setHasMore(false);
})
.finally(() => {
if (cancelled || fetchGenRef.current !== generation) return;
if (fetchGenRef.current !== generation) return;
setLoading(false);
});

return () => {
cancelled = true;
};
}, [inView, loading, hasMore]);

// Reset: replace all data, update hasMore, reset page counter.
Expand Down
Loading