import React from "react"; import Link from "next/link"; import Image from "next/image"; import { ExternalLink } from "lucide-react"; import { client, urlFor } from "@/lib/sanity"; import { Card, CardContent } from "../ui/card"; import { Pagination, PaginationContent, PaginationItem, PaginationLink, PaginationNext, PaginationPrevious } from "@/components/ui/pagination"; import { format } from "date-fns"; interface BlogPostcard { title: string; smallDescription: string; currentSlug: string; titleImage: string; _createdAt: string; } interface BlogCardInterface { page: number; } const BlogCards: React.FC = async (props) => { "use server"; // Change in /blog/page/[id] route and in /api/revalidate route too! const cardsPerPage = 6; const currentPage = props.page; const query = `*[_type == 'blog'] | order(_createdAt desc) { title, smallDescription, "currentSlug": slug.current, titleImage, _createdAt }[${(currentPage - 1) * cardsPerPage}...${currentPage * cardsPerPage}]`; const posts: BlogPostcard[] = await client.fetch( query, {}, { cache: "no-store" } ); const totalPostsQuery = `count(*[_type == 'blog'])`; const totalPosts: number = await client.fetch( totalPostsQuery, {}, { cache: "no-store" } ); const totalPages = Math.ceil(totalPosts / cardsPerPage); let begPage = currentPage - 2; let endPage = currentPage + 2; if (endPage > totalPages) { begPage -= endPage - totalPages; endPage = totalPages; } if (begPage < 1) { endPage += 1 - begPage; begPage = 1; } return ( <>
{posts.map((post, idx) => { const formattedDate = format( new Date(post._createdAt), "MMMM d, yyyy" ); const truncatedDescription = post.smallDescription.length > 130 ? post.smallDescription.substring(0, 130) + "..." : post.smallDescription; return (
{post.title}

{post.title}

{truncatedDescription}

Published on: {formattedDate}

); })}
{totalPages > 1 && ( {currentPage > 1 && ( )} {Array.from({ length: totalPages > 5 ? 5 : totalPages }).map( (_, i) => ( {begPage + i} ) )} {currentPage < totalPages && ( )} )}
); }; export default BlogCards;