fixed code
This commit is contained in:
@@ -1,8 +1,9 @@
|
||||
import { useState, useRef, useEffect, useCallback } from "react";
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { compressImage } from "../utils/compressImage";
|
||||
import { getImageUrl } from "../config/authConstants";
|
||||
|
||||
const MAX_SIZE_MB = 5;
|
||||
export const MAX_SIZE_MB = 5;
|
||||
export const ACCEPT = "image/jpeg,image/png,image/webp";
|
||||
|
||||
/**
|
||||
@@ -18,6 +19,7 @@ function generateImageId() {
|
||||
}
|
||||
|
||||
export function useImageUpload(existingUrls = []) {
|
||||
const { t } = useTranslation();
|
||||
const [images, setImages] = useState([]);
|
||||
const [imgError, setImgError] = useState("");
|
||||
const [compressing, setCompressing] = useState(false);
|
||||
@@ -45,11 +47,11 @@ export function useImageUpload(existingUrls = []) {
|
||||
|
||||
for (const file of files) {
|
||||
if (!file.type.startsWith("image/")) {
|
||||
setImgError("Images only (JPEG, PNG, WebP)");
|
||||
setImgError(t('imageUpload.invalidType'));
|
||||
return;
|
||||
}
|
||||
if (file.size > MAX_SIZE_MB * 1024 * 1024) {
|
||||
setImgError(`File too large — max ${MAX_SIZE_MB} MB`);
|
||||
setImgError(t('imageUpload.tooLarge', { maxSize: MAX_SIZE_MB }));
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -66,12 +68,12 @@ export function useImageUpload(existingUrls = []) {
|
||||
}));
|
||||
setImages(prev => [...prev, ...newImages]);
|
||||
} catch {
|
||||
setImgError("Failed to process image");
|
||||
setImgError(t('imageUpload.processingFailed'));
|
||||
} finally {
|
||||
setCompressing(false);
|
||||
if (fileInputRef.current) fileInputRef.current.value = "";
|
||||
}
|
||||
}, []);
|
||||
}, [t]);
|
||||
|
||||
const removeImage = useCallback((id) => {
|
||||
setImages(prev => {
|
||||
@@ -91,15 +93,22 @@ export function useImageUpload(existingUrls = []) {
|
||||
return images.filter(i => i.isExisting).map(i => i.serverUrl);
|
||||
}, [images]);
|
||||
|
||||
// Ref нужен, чтобы cleanup при размонтировании видел АКТУАЛЬНЫЙ список
|
||||
// изображений, а не тот, что был на момент первого рендера (иначе
|
||||
// object URL'ы для реально загруженных файлов никогда не отзываются).
|
||||
const imagesRef = useRef(images);
|
||||
useEffect(() => {
|
||||
imagesRef.current = images;
|
||||
}, [images]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
images.forEach(img => {
|
||||
imagesRef.current.forEach(img => {
|
||||
if (!img.isExisting && img.preview) {
|
||||
URL.revokeObjectURL(img.preview);
|
||||
}
|
||||
});
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
return {
|
||||
|
||||
Reference in New Issue
Block a user