"use client"; import { useEffect, useState } from "react"; import Image from "next/image"; import { getListArticle } from "@/service/article"; // Type dari API type Article = { id: number; title: string; description: string; categoryName: string; createdAt: string; createdByName: string; thumbnailUrl: string; categories: { title: string }[]; files: { fileUrl: string; file_alt: string }[]; }; export default function News() { const [articlesByCategory, setArticlesByCategory] = useState< Record >({}); const [loading, setLoading] = useState(true); const [visiblePosts, setVisiblePosts] = useState>({}); useEffect(() => { fetchArticles(); }, []); async function fetchArticles() { try { const req = { limit: "20", // ambil lebih banyak, nanti dibagi per kategori page: 1, search: "", categorySlug: "", sort: "desc", isPublish: true, sortBy: "created_at", }; const res = await getListArticle(req); const allArticles: Article[] = res?.data?.data || []; // Group by category const grouped: Record = {}; allArticles.forEach((a) => { const cat = a.categoryName || a.categories?.[0]?.title || "Lainnya"; if (!grouped[cat]) grouped[cat] = []; grouped[cat].push(a); }); setArticlesByCategory(grouped); // Set default visiblePosts untuk setiap kategori const initialVisible: Record = {}; Object.keys(grouped).forEach((cat) => { initialVisible[cat] = 2; // awal 2 post bawah }); setVisiblePosts(initialVisible); } catch (error) { console.error("Gagal ambil artikel:", error); } finally { setLoading(false); } } return (
{loading &&

Memuat data...

} {!loading && Object.keys(articlesByCategory).map((category) => { const posts = articlesByCategory[category]; if (!posts?.length) return null; const postsTop = posts.slice(0, 2); // 2 atas const postsBottom = posts.slice(2); // sisanya return (
{/* Header kategori */}
{category}
{/* Posts atas */} {postsTop.map((post) => ( ))} {/* Banner Kolom PPS */}
Kolom PPS
{/* Posts bawah (pakai visiblePosts[category]) */} {postsBottom.slice(0, visiblePosts[category] || 2).map((post) => ( ))} {/* Tombol Load More */} {(visiblePosts[category] || 2) < postsBottom.length && (
)}
); })}
); } function PostItem({ post }: { post: Article }) { return (
{/* Gambar */}
{post.files?.[0]?.file_alt
{/* Konten */}

{post.title}

by {post.createdByName} •{" "} {new Date(post.createdAt).toLocaleDateString("id-ID", { day: "numeric", month: "long", year: "numeric", })}{" "} • 💬 0

{post.description}

); }