This repository has been archived on 2026-11-23. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
hope-events/frontend/src/hooks/useQRScanner.ts
T
joshuaandClaude Opus 5.5 545f3d913e Add shared API types and type the smaller frontend pages
Expand src/types with User, Event, EventOption, Registration, Payment,
Ticket, paginated results and dashboard stats, modelled on the Prisma
schema. apiFetch now defaults to unknown instead of any. Dashboard
loaders are wrapped in useCallback so their effects can list them as
dependencies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:10:01 +02:00

81 lines
2.5 KiB
TypeScript

"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import { BrowserQRCodeReader } from "@zxing/browser";
export type UseQRScannerOptions = {
onResult?: (text: string) => void;
onError?: (error: unknown) => void;
};
// Hook to decode QR codes from a HTMLVideoElement using @zxing/browser
export function useQRScanner(videoEl: HTMLVideoElement | null, opts: UseQRScannerOptions = {}) {
const { onResult, onError } = opts;
const [active, setActive] = useState(false);
const [permissionError, setPermissionError] = useState<string | null>(null);
const readerRef = useRef<BrowserQRCodeReader | null>(null);
const cancelRef = useRef<(() => void) | undefined>(undefined);
const stop = useCallback(() => {
cancelRef.current?.();
cancelRef.current = undefined;
}, []);
const toggle = useCallback(() => setActive((p) => !p), []);
useEffect(() => {
readerRef.current = new BrowserQRCodeReader();
return () => {
stop();
readerRef.current = null;
};
}, [stop]);
useEffect(() => {
let cancelled = false;
async function run() {
setPermissionError(null);
try {
// Start decode loop
const reader = readerRef.current!;
const scan = async () => {
if (cancelled) return;
try {
if (!videoEl) return;
const result = await reader.decodeOnceFromVideoElement(videoEl);
const text = result?.getText() ?? "";
if (text) onResult?.(text);
} catch {
// Ignore transient decode errors and retry
} finally {
if (!cancelled && active) setTimeout(scan, 200);
}
};
scan();
cancelRef.current = () => {
cancelled = true;
};
} catch (err) {
// getUserMedia rejects with a DOMException whose `name` says why.
const name = (err as { name?: string } | null)?.name;
if (name === "NotAllowedError") {
setPermissionError("Camera permission denied. Please enable camera access.");
} else if (name === "NotFoundError") {
setPermissionError("No suitable camera found. Try a device with a back camera.");
} else {
setPermissionError("Unable to access camera.");
}
onError?.(err);
setActive(false);
}
}
if (active && videoEl) run();
else stop();
}, [active, onError, onResult, stop, videoEl]);
return { active, toggle, stop, permissionError };
}