'use client'; import { useEffect, useState } from 'react'; import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card" import Link from "next/link" import strings from "@/strings.json" import { formatDistanceToNow, format } from 'date-fns' type Post = { id: string; title: string; description: string; date: number; slug: string; }; export default function CategorySlug() { const [posts, setPosts] = useState([]); const [error, setError] = useState(''); const [category, setCategory] = useState('Category View'); // TODO: needs a better title const [loading, setLoading] = useState(true); useEffect(() => { console.log(strings.logsFetchPostList); (async () => { try { const catReq = await fetch(`http://localhost:3001/api/categories/fetchList`, { method: 'GET', }); const postReq = await fetch(`http://localhost:3001/api/posts/fetchList`, { method: 'GET', }); if (!catReq.ok) { throw new Error(`${strings.errorsFetchCategoryListFailCtx} ${catReq.status}`); } if (!postReq.ok) { throw new Error(`${strings.errorsFetchPostListFailCtx} ${postReq.status}`); } const catData = await catReq.json(); const postData = await postReq.json(); if (!catData) { setError(strings.errorsFetchCategoryListFail); } else { console.log(strings.logsOnFetchedCategory); const slug = window.location.pathname.split('/').slice(-1)[0]; const category = catData.categories.find((cat: { slug: string }) => cat.slug === slug); if (category) { console.log(`${strings.logsOnFoundCategory} ${category.name}`); setCategory(category.name); if (postData.success === false) { if (postData.message) { throw new Error(postData.message); } else { throw new Error(strings.errorsUnknownError); } } else { const sortedPosts = postData.posts.sort((a: Post, b: Post) => b.date - a.date); setPosts(sortedPosts); } } else { setError(strings.errorsFetchCategoryNotFound); throw new Error(strings.errorsFetchCategoryNotFound); } } } catch (error) { console.error(strings.errorsFetchPostListErrCtxFancy, error); setError(strings.errorsFetchPostListErr); } finally { setLoading(false); } })(); }, []); interface FormatDate { (timestamp: number): string; } const formatDate: FormatDate = (timestamp) => { const date = new Date(timestamp * 1000); const now = new Date(); if (date.getFullYear() !== now.getFullYear()) { return format(date, 'MM/DD/YYYY'); } else { return formatDistanceToNow(date, { addSuffix: true }); } }; return (
{strings.recentPostsPublishedOnLabel} {formatDate(post.date)}