From 441b20bccf10b46072aee6d320451e96eba5737c Mon Sep 17 00:00:00 2001 From: vyshnav Date: Wed, 2 Oct 2024 15:09:04 +0530 Subject: [PATCH] Refactor QR code scanner to use @yudiel/react-qr-scanner --- src/app/admin/verify/page.tsx | 50 ++++++++++++++++++++--------------- 1 file changed, 28 insertions(+), 22 deletions(-) diff --git a/src/app/admin/verify/page.tsx b/src/app/admin/verify/page.tsx index 13dfa50..2ff48ba 100644 --- a/src/app/admin/verify/page.tsx +++ b/src/app/admin/verify/page.tsx @@ -1,10 +1,10 @@ "use client"; - import { useState, useEffect } from "react"; -import { QrReader } from "react-qr-reader"; +import { Scanner } from "@yudiel/react-qr-scanner"; import { useRouter } from "next/navigation"; +import { IDetectedBarcode } from "@yudiel/react-qr-scanner"; -export default function QRCodeScanner() { +const QRCodeScanner = () => { const [isMobile, setIsMobile] = useState(false); const [error, setError] = useState(null); const router = useRouter(); @@ -17,27 +17,34 @@ export default function QRCodeScanner() { userAgent.toLowerCase() ); }; - setIsMobile(checkMobile()); }, []); - const handleScan = (result: string | null) => { - if (result) { - // Validate URL before redirecting - try { - new URL(result); - router.push(result); - } catch { - setError("Invalid QR code. Please scan a valid URL."); + const handleScan = (detectedCodes: IDetectedBarcode[]) => { + if (detectedCodes.length > 0) { + const result = detectedCodes[0].rawValue; + if (result) { + try { + // Validate if the scanned result is a valid URL + const url = new URL(result); + // Redirect to the scanned URL + router.push(url.toString()); + } catch { + setError("Invalid QR code. Please scan a valid URL."); + } } } }; - const handleError = (error: Error) => { - setError("Error accessing camera: " + error.message); + const handleError = (error: unknown) => { + if (error instanceof Error) { + setError("Error accessing camera: " + error.message); + } else { + setError("An unknown error occurred."); + } }; - if (!isMobile) { + if (isMobile) { return (
@@ -58,12 +65,9 @@ export default function QRCodeScanner() { {error ? (

{error}

) : ( - { - if (result) { - handleScan(result?.text); - } - }} + )} @@ -73,4 +77,6 @@ export default function QRCodeScanner() {
); -} +}; + +export default QRCodeScanner;