54 lines
1.5 KiB
TypeScript
54 lines
1.5 KiB
TypeScript
import { useEffect, useState } from 'react';
|
|
import { apiBlob } from '../api/client';
|
|
|
|
// Obiekty URL trzymamy w buforze na czas życia karty — ten sam obraz potrafi
|
|
// pojawić się kilka razy (okładka na liście + w szczegółach).
|
|
const srcCache = new Map<string, Promise<string>>();
|
|
|
|
function loadObjectUrl(url: string): Promise<string> {
|
|
let pending = srcCache.get(url);
|
|
if (!pending) {
|
|
pending = apiBlob(url).then((blob) => URL.createObjectURL(blob));
|
|
srcCache.set(url, pending);
|
|
pending.catch(() => srcCache.delete(url));
|
|
}
|
|
return pending;
|
|
}
|
|
|
|
interface AuthImageProps {
|
|
/** Ścieżka względna API (np. `/gyms/x/photos/y`). */
|
|
src: string | null | undefined;
|
|
alt: string;
|
|
className?: string;
|
|
}
|
|
|
|
/**
|
|
* Zdjęcia siłowni serwuje chroniony endpoint (Authorization), więc zwykły
|
|
* <img src> nie przejdzie — pobieramy blob przez `apiBlob` i wyświetlamy z
|
|
* URL.createObjectURL. Błąd poboru = pusty render (bez errorów w konsoli).
|
|
*/
|
|
export function AuthImage({ src, alt, className }: AuthImageProps) {
|
|
const [objectUrl, setObjectUrl] = useState<string | null>(null);
|
|
|
|
useEffect(() => {
|
|
if (!src) {
|
|
setObjectUrl(null);
|
|
return;
|
|
}
|
|
let active = true;
|
|
loadObjectUrl(src)
|
|
.then((url) => {
|
|
if (active) setObjectUrl(url);
|
|
})
|
|
.catch(() => {
|
|
if (active) setObjectUrl(null);
|
|
});
|
|
return () => {
|
|
active = false;
|
|
};
|
|
}, [src]);
|
|
|
|
if (!src || !objectUrl) return null;
|
|
return <img src={objectUrl} alt={alt} className={className} />;
|
|
}
|