"use client"; import { formatDate } from "@/utils"; import * as ScrollArea from "@radix-ui/react-scroll-area"; import { useState, useEffect } from "react"; import { Article } from "../lib/prisma.ts"; import useSWR from "swr"; import { ApiResponse } from "../lib/feed.ts"; const fetcher = (url: string) => fetch(url).then((r) => r.json()); const Feed = ({ className, variant = "col", icon, title, initialData, }: { className?: string; variant?: "row" | "col"; title: string; icon: keyof typeof ICON_DICT; initialData: Article[]; }) => { const filters = ["latest", "day", "week", "month"] as const; const [content, setContent] = useState>(initialData); const [selectedFilter, setSelectedFilter] = useState<(typeof filters)[number]>("latest"); const [currentPage, setCurrentPage] = useState(0); const Icon = ICON_DICT[icon]; const { data: swrData, error } = useSWR, any>( `/api/feed?filter=${selectedFilter}&page=${currentPage}`, fetcher, { revalidateOnFocus: false, revalidateIfStale: false, revalidateOnReconnect: false, shouldRetryOnError: false, fallbackData: currentPage === 0 ? { data: initialData, current: 0, next: 5 } : undefined, // Use initialData only for the first page }, ); useEffect(() => { if (swrData && currentPage !== 0) { setContent((prevContent) => [...prevContent, ...swrData.data]); } else if (swrData) { setContent(swrData.data); } }, [swrData, currentPage]); const handleFilterChange = (filter: (typeof filters)[number]) => { setSelectedFilter(filter); setCurrentPage(0); // Reset to the first page when the filter changes }; const handleLoadMore = () => { setCurrentPage((prevPage) => prevPage + 1); // Increment page number to fetch next set of data }; if (error) { return
Failed to load
; } return (
{content.map((item, index) => { return (
{formatDate(item.createdAt)}

{item.title}

); })} {swrData?.next ? ( ) : null}
); }; export default Feed; const PaperIcon = ({ className }: { className?: string }) => { return ( ); }; const TopArrowLodashIcon = ({ className }: { className?: string }) => { return ( ); }; const TrendUpIcon = ({ className }: { className?: string }) => { return ( ); }; const ICON_DICT = { "paper-icon": PaperIcon, "trend-up-icon": TrendUpIcon, "top-arrow-icon": TopArrowLodashIcon, } as const;