I'm facing an issue with the useEffect hook in my React component that utilizes the Capacitor Camera plugin. The problem occurs when there are errors in my code, specifically when dealing with wrong image selection or closing the camera. It seems like the useEffect hook does not reset properly, preventing me from remounting the component when errors are present. Everything works as expected when there are no errors.
Here is my component.
interface TakePhotoProps {
onCaptureImage: (capturedImage: File) => void;
}
const TakePhoto: FC<TakePhotoProps> = ({ onCaptureImage }) => {
const [, setCapturedImage] = useState<File | undefined>();
var flag = false;
const { t } = useTranslation();
const { Toast } = useToast();
const openCamera = async () => {
try {
defineCustomElements(window);
const capturedPhoto = await Camera.getPhoto({
quality: 90,
resultType: CameraResultType.DataUrl,
source: CameraSource.Camera,
width: 620,
height: 480,
});
if (capturedPhoto && capturedPhoto.dataUrl) {
const blob = await fetch(capturedPhoto.dataUrl).then((res) => res.blob());
const isValidFileType = /^image\/(jpeg|jpg|png|gif)$/.test(blob.type);
if (isValidFileType) {
const imageFile = new File([blob], 'image.jpg', { type: 'image/jpeg' });
let fileToScan: File = imageFile;
setCapturedImage(fileToScan);
onCaptureImage(fileToScan);
} else {
Toast.error(t('error-select-image'));
}
}
} catch (error) {}
};
useEffect(() => {
console.log(flag);
if (!flag) {
openCamera();
flag = true;
}
}, [flag]);
return <></>;
};
export default TakePhoto;