67 lines
1.5 KiB
TypeScript
67 lines
1.5 KiB
TypeScript
import { HTTPSTATUS } from '@/constants';
|
|
import { apiGetPhoto } from '@/services/slave/sgw/PhotoController';
|
|
import { Image, Spin } from 'antd';
|
|
import { useEffect, useRef, useState } from 'react';
|
|
|
|
export const FishImage = ({
|
|
fishId,
|
|
alt,
|
|
isReload,
|
|
}: {
|
|
fishId: string;
|
|
alt: string;
|
|
isReload: boolean;
|
|
}) => {
|
|
const [url, setUrl] = useState<string>('');
|
|
const [loading, setLoading] = useState(true);
|
|
const objectUrlRef = useRef<string>('');
|
|
|
|
useEffect(() => {
|
|
let isMounted = true;
|
|
|
|
const fetchImage = async () => {
|
|
try {
|
|
const resp = await apiGetPhoto('fish', fishId);
|
|
let objectUrl = '';
|
|
if (resp.status === HTTPSTATUS.HTTP_SUCCESS) {
|
|
const blob = new Blob([resp.data], { type: 'image/jpeg' });
|
|
objectUrl = URL.createObjectURL(blob);
|
|
objectUrlRef.current = objectUrl;
|
|
} else {
|
|
throw new Error('Failed to fetch image');
|
|
}
|
|
|
|
if (isMounted) {
|
|
setUrl(objectUrl);
|
|
setLoading(false);
|
|
}
|
|
} catch (error) {
|
|
// console.log('Error: ', error);
|
|
setUrl('');
|
|
if (isMounted) {
|
|
setLoading(false);
|
|
}
|
|
}
|
|
};
|
|
|
|
fetchImage();
|
|
|
|
return () => {
|
|
isMounted = false;
|
|
if (objectUrlRef.current) {
|
|
URL.revokeObjectURL(objectUrlRef.current);
|
|
}
|
|
};
|
|
}, [fishId, isReload]);
|
|
|
|
if (loading) {
|
|
return <Spin size="small" />;
|
|
}
|
|
|
|
if (!url) {
|
|
return <span>-</span>;
|
|
}
|
|
|
|
return <Image height={50} width={50} src={url} alt={alt} />;
|
|
};
|