FIX: FetchOnScroll functionality on AllCategoriesPage - BUG: duplicate categories appear

This commit is contained in:
Chris-1010
2025-02-27 01:25:38 +00:00
parent eaf6e3d693
commit 6f2c294257
2 changed files with 55 additions and 38 deletions

View File

@@ -2,20 +2,29 @@ import { useEffect } from "react";
export function fetchContentOnScroll(callback: () => void, hasMoreData: boolean) { export function fetchContentOnScroll(callback: () => void, hasMoreData: boolean) {
useEffect(() => { useEffect(() => {
const root = document.querySelector("#root") as HTMLElement;
const handleScroll = () => { const handleScroll = () => {
if (!hasMoreData) return; // Don't trigger scroll if no more data if (!hasMoreData) return; // Don't trigger scroll if no more data
const scrollPosition = window.innerHeight + document.documentElement.scrollTop;
const scrollHeight = document.documentElement.scrollHeight; // Use properties of the element itself, not document
const scrollPosition = root.scrollTop + root.clientHeight;
const scrollHeight = root.scrollHeight;
if (scrollPosition >= scrollHeight * 0.9) { if (scrollPosition >= scrollHeight * 0.9) {
callback(); // Trigger data fetching when 90% scroll is reached callback(); // Trigger data fetching when 90% scroll is reached
setTimeout(() => {
// Delay to prevent multiple fetches
root.scrollTop = root.scrollTop - 1;
}, 100);
} }
}; };
window.addEventListener("scroll", handleScroll); // Add scroll event listener to the root element
root.addEventListener("scroll", handleScroll);
return () => { return () => {
window.removeEventListener("scroll", handleScroll); // Cleanup on unmount root.removeEventListener("scroll", handleScroll); // Cleanup on unmount
}; };
}, [callback, hasMoreData]); }, [callback, hasMoreData]);
} }

View File

@@ -1,99 +1,107 @@
import React, { useEffect, useState, useRef } from "react"; import React, { useRef, useState, useEffect } from "react";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import ListRow from "../components/Layout/ListRow"; import ListRow from "../components/Layout/ListRow";
import DynamicPageContent from "../components/Layout/DynamicPageContent"; import DynamicPageContent from "../components/Layout/DynamicPageContent";
import { fetchContentOnScroll } from "../hooks/fetchContentOnScroll"; import { fetchContentOnScroll } from "../hooks/fetchContentOnScroll";
import LoadingScreen from "../components/Layout/LoadingScreen"; import LoadingScreen from "../components/Layout/LoadingScreen";
import { CategoryType } from "../types/CategoryType";
interface CategoryData {
type: "category";
id: number;
title: string;
viewers: number;
thumbnail: string;
}
const AllCategoriesPage: React.FC = () => { const AllCategoriesPage: React.FC = () => {
const [categories, setCategories] = useState<CategoryData[]>([]);
const navigate = useNavigate(); const navigate = useNavigate();
const [allCategories, setAllCategories] = useState<CategoryType[]>([]);
const [categoryOffset, setCategoryOffset] = useState(0); const [categoryOffset, setCategoryOffset] = useState(0);
const [noCategories, setNoCategories] = useState(12);
const [hasMoreData, setHasMoreData] = useState(true); const [hasMoreData, setHasMoreData] = useState(true);
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
const listRowRef = useRef<any>(null); const listRowRef = useRef<any>(null);
const fetchCategories = async () => { const fetchCategories = async () => {
if (isLoading) return; if (isLoading && categoryOffset > 0) return [];
try { try {
console.log(`Fetching categories with offset: ${categoryOffset}`);
const response = await fetch( const response = await fetch(
`/api/categories/popular/${noCategories}/${categoryOffset}` `/api/categories/popular/12/${categoryOffset}`
); );
if (!response.ok) { if (!response.ok) throw new Error("Failed to fetch categories");
throw new Error("Failed to fetch categories");
}
const data = await response.json(); const data = await response.json();
console.log("Categories fetched:", data.length);
if (data.length === 0) { if (data.length === 0) {
setHasMoreData(false); setHasMoreData(false);
return []; return [];
} }
setCategoryOffset((prev) => prev + data.length); setCategoryOffset(categoryOffset + data.length);
const processedCategories = data.map((category: any) => ({ const newCategories = data.map((category: any) => ({
type: "category" as const, type: "category" as const,
id: category.category_id, id: category.category_id,
title: category.category_name, title: category.category_name,
viewers: category.num_viewers, viewers: category.num_viewers || 0,
thumbnail: `/images/category_thumbnails/${category.category_name thumbnail: `/images/category_thumbnails/${category.category_name
.toLowerCase() .toLowerCase()
.replace(/ /g, "_")}.webp`, .replace(/ /g, "_")}.webp`,
})); }));
setCategories((prev) => [...prev, ...processedCategories]); return newCategories;
return processedCategories; } catch (err) {
} catch (error) { console.error("Error fetching categories:", err);
console.error("Error fetching categories:", error); setHasMoreData(false);
return []; return [];
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }
}; };
// Initial load
useEffect(() => { useEffect(() => {
fetchCategories(); const initialLoad = async () => {
const initialCategories = await fetchCategories();
setAllCategories(initialCategories);
};
initialLoad();
}, []); }, []);
const loadOnScroll = async () => { const loadMoreCategories = async () => {
if (hasMoreData && listRowRef.current) { if (!hasMoreData || (isLoading && categoryOffset > 0)) return;
const newCategories = await fetchCategories();
if (newCategories?.length > 0) { const newCategories = await fetchCategories();
if (newCategories.length > 0) {
setAllCategories(prev => [...prev, ...newCategories]);
if (listRowRef.current && listRowRef.current.addMoreItems) {
listRowRef.current.addMoreItems(newCategories); listRowRef.current.addMoreItems(newCategories);
} }
} }
}; };
fetchContentOnScroll(loadOnScroll, hasMoreData); // Set up infinite scroll
fetchContentOnScroll(loadMoreCategories, hasMoreData);
if (hasMoreData && !categories.length) return <LoadingScreen />;
const handleCategoryClick = (categoryName: string) => { const handleCategoryClick = (categoryName: string) => {
console.log(categoryName);
navigate(`/category/${categoryName}`); navigate(`/category/${categoryName}`);
}; };
if (isLoading && allCategories.length === 0) return <LoadingScreen />;
return ( return (
<DynamicPageContent className="min-h-screen"> <DynamicPageContent className="min-h-screen">
<ListRow <ListRow
ref={listRowRef} ref={listRowRef}
type="category" type="category"
title="All Categories" title="All Categories"
items={categories} items={allCategories}
onItemClick={handleCategoryClick} onItemClick={handleCategoryClick}
extraClasses="bg-[var(--recommend)] text-center" extraClasses="bg-[var(--recommend)] text-center"
itemExtraClasses="w-[20vw]" itemExtraClasses="w-[20vw]"
wrap={true} wrap={true}
/> />
{!hasMoreData && allCategories.length > 0 && (
<div className="text-center text-gray-500 p-4">
No more categories to load
</div>
)}
</DynamicPageContent> </DynamicPageContent>
); );
}; };