import { useState, useEffect } from 'react';
const checkImage = (url: string): Promise<boolean> => {
return new Promise(resolve => {
const image = new Image();
image.onload = () => resolve(true);
image.onerror = () => resolve(false);
image.src = `${url}&r=${Math.random()}`; // 캐시 방지
});
};
export const useImagePolling = (
url: string,
isGenerationComplete: boolean,
interval: number = 5000,
): boolean => {
const [imageLoaded, setImageLoaded] = useState<boolean>(false);
useEffect(() => {
let isMounted = true;
let timeoutId: number;
const pollImage = async (): Promise<void> => {
if (!isGenerationComplete) {
if (isMounted) {
timeoutId = window.setTimeout(pollImage, interval);
}
return;
}
const exists = await checkImage(url);
if (exists && isMounted) {
setImageLoaded(true);
} else if (isMounted) {
timeoutId = window.setTimeout(pollImage, interval);
}
};
pollImage();
return () => {
isMounted = false;
if (timeoutId) {
window.clearTimeout(timeoutId);
}
};
}, [url, interval, isGenerationComplete]);
return imageLoaded;
};