import { useEffect, useMemo, useState } from "react"; import { Link, useNavigate, useParams } from "react-router-dom"; import { getAllImagesByNoticeId, getNoticeById } from "../api/notices"; import { useAuthStore } from "../store/authStore"; import { useNoticesStore } from "../store/noticesStore"; export default function NoticeDetails() { const { id } = useParams(); const navigate = useNavigate(); const { user_id } = useAuthStore(); const { notices, deleteNotice, fetchNotices } = useNoticesStore(); const [notice, setNotice] = useState(null); const [images, setImages] = useState([]); const [isLoading, setIsLoading] = useState(true); const [isImagesLoading, setIsImagesLoading] = useState(true); useEffect(() => { let isMounted = true; const loadNotice = async () => { setIsLoading(true); try { let found = notices.find((item) => String(item.noticeId) === String(id)); if (!found) { found = await getNoticeById(id); } if (isMounted) { setNotice(found); } } finally { if (isMounted) { setIsLoading(false); } } }; const loadImages = async () => { setIsImagesLoading(true); try { const imageUrls = await getAllImagesByNoticeId(id); if (isMounted) { setImages(imageUrls); } else { imageUrls.forEach((imageUrl) => { if (typeof imageUrl === "string" && imageUrl.startsWith("blob:")) { URL.revokeObjectURL(imageUrl); } }); } } finally { if (isMounted) { setIsImagesLoading(false); } } }; loadNotice(); loadImages(); return () => { isMounted = false; }; }, [id, notices]); useEffect(() => { return () => { images.forEach((imageUrl) => { if (typeof imageUrl === "string" && imageUrl.startsWith("blob:")) { URL.revokeObjectURL(imageUrl); } }); }; }, [images]); const isOwner = useMemo(() => { if (!notice) { return false; } return String(notice.clientId) === String(user_id); }, [notice, user_id]); const handleDelete = async () => { const confirmed = window.confirm("Usunac ogloszenie?"); if (!confirmed) { return; } await deleteNotice(Number(id)); await fetchNotices(); navigate("/dashboard/my-notices"); }; if (isLoading) { return (
{notice.category}
{notice.description}
{notice.price} zl