import { useEffect, useState } from "react"; import axios from "axios"; import Markdown from "react-markdown"; import { useLanguageStore } from "@/stores/languageStore"; import { useTranslation } from 'react-i18next'; type TranslatedField = string | Record; type NewsPost = { id: number; slug: string; title: TranslatedField; excerpt: TranslatedField | null; content: TranslatedField; published_at: string; }; type PaginatedResponse = { data: T[]; }; function resolveTranslation( field: TranslatedField | null | undefined, locale: string ): string { if (!field) return ""; if (typeof field === "string") { return field; } if (field[locale]) return field[locale]; if (field["en"]) return field["en"]; const first = Object.values(field)[0]; return first ?? ""; } function formatDate(value: string | null | undefined, locale: string): string { if (!value) return ""; const date = new Date(value); if (Number.isNaN(date.getTime())) return ""; return new Intl.DateTimeFormat(locale, { day: "2-digit", month: "2-digit", year: "numeric", }).format(date); } type NewsListProps = { initialLimit?: number; }; export default function NewsList({ initialLimit = 3 }: NewsListProps) { const locale = useLanguageStore((s) => s.locale); const { t } = useTranslation("common"); const [items, setItems] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [limit, setLimit] = useState(initialLimit); useEffect(() => { let active = true; (async () => { try { setLoading(true); setError(null); const res = await axios.get | NewsPost[]>( "/api/news", { withCredentials: true, headers: { Accept: "application/json" }, params: { lang: locale, limit }, // <<<< tady se pošle jazyk na backend } ); if (!active) return; const data = Array.isArray(res.data) ? res.data : (res.data as PaginatedResponse).data; setItems(data); } catch { if (!active) return; setError("Nepodařilo se načíst novinky."); } finally { if (active) setLoading(false); } })(); return () => { active = false; }; // <<<< refetch při změně jazyka }, [locale, limit]); if (loading) return
Načítám novinky…
; if (error) return
{error}
; if (items.length === 0) { return; } return (
{items.map((post) => { const title = resolveTranslation(post.title, locale); const content = resolveTranslation(post.content, locale); return (

{title}

{post.published_at && (

{formatDate(post.published_at, locale)}

)}
{content}
); })} {items.length >= limit && (
)}
); }