diff --git a/src/components/stock/QRScannerDialog.tsx b/src/components/stock/QRScannerDialog.tsx index 75c662b..19ed6c7 100644 --- a/src/components/stock/QRScannerDialog.tsx +++ b/src/components/stock/QRScannerDialog.tsx @@ -10,18 +10,13 @@ import { DialogDescription, } from "@/components/ui/dialog" -interface QRScannerDialogProps { - open: boolean - onOpenChange: (open: boolean) => void - onScanSuccess: (decodedText: string) => void -} +const SCANNER_ID = "html5-qrcode-reader"; -const QRScannerDialog = ({ open, onOpenChange, onScanSuccess }: QRScannerDialogProps) => { +// This component is only mounted when the dialog is open, ensuring the div exists. +const Scanner = ({ onScanSuccess }: { onScanSuccess: (decodedText: string) => void }) => { useEffect(() => { - if (!open) return; - const scanner = new Html5QrcodeScanner( - "reader", // The ID of the element to render the scanner in + SCANNER_ID, { qrbox: { width: 250, @@ -33,12 +28,11 @@ const QRScannerDialog = ({ open, onOpenChange, onScanSuccess }: QRScannerDialogP ); const handleSuccess = (decodedText: string) => { - scanner.clear(); + // Let the cleanup function handle stopping the scanner when the component unmounts. onScanSuccess(decodedText); }; const handleError = (error: any) => { - // Don't log common errors like QR code not found if (typeof error !== 'string' || !error.includes('No QR code found')) { console.error("QR Scanner Error:", error); } @@ -46,16 +40,26 @@ const QRScannerDialog = ({ open, onOpenChange, onScanSuccess }: QRScannerDialogP scanner.render(handleSuccess, handleError); - // Cleanup function to stop the scanner when the component unmounts or dialog closes + // Cleanup function to stop the scanner when the component unmounts. return () => { - if (scanner) { - scanner.clear().catch(error => { - console.error("Failed to clear scanner.", error); - }); - } + scanner.clear().catch(error => { + // This can sometimes throw an error if the component is already gone. + // We can safely ignore it. + console.log("Scanner cleared or already gone."); + }); }; - }, [open, onScanSuccess]); + }, [onScanSuccess]); + return
; +}; + +interface QRScannerDialogProps { + open: boolean + onOpenChange: (open: boolean) => void + onScanSuccess: (decodedText: string) => void +} + +const QRScannerDialog = ({ open, onOpenChange, onScanSuccess }: QRScannerDialogProps) => { return ( @@ -65,7 +69,8 @@ const QRScannerDialog = ({ open, onOpenChange, onScanSuccess }: QRScannerDialogP Point your camera at a QR code to scan it. -
+ {/* Conditionally render the Scanner component only when the dialog is open */} + {open && }
);