Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(271): invalidate the ref in order to fix camera running in the background issue #279

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 22 additions & 4 deletions src/QrReader/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,14 @@ export const useQrReader: UseQrReaderHook = ({
onResult,
videoId,
}) => {
const controlsRef: MutableRefObject<IScannerControls> = useRef(null);

/**
* The ref has 3 possible states:
* undefined - reader is not initialized
* null - useEffect cleanup was called so we should throw an error if the decode Promise resolves
* IScannerControls - reader is initialized and ready to be used
*/
const controlsRef: MutableRefObject<IScannerControls | null | undefined> =
useRef(undefined);
useEffect(() => {
const codeReader = new BrowserQRCodeReader(null, {
delayBetweenScanAttempts,
Expand All @@ -33,10 +39,17 @@ export const useQrReader: UseQrReaderHook = ({
codeReader
.decodeFromConstraints({ video }, videoId, (result, error) => {
if (isValidType(onResult, 'onResult', 'function')) {
if (controlsRef.current === null) {
throw new Error('Component is unmounted');
}
onResult(result, error, codeReader);
}
})
.then((controls: IScannerControls) => (controlsRef.current = controls))
.then((controls: IScannerControls) => {
if (controlsRef.current === undefined) {
controlsRef.current = controls;
}
})
.catch((error: Error) => {
if (isValidType(onResult, 'onResult', 'function')) {
onResult(null, error, codeReader);
Expand All @@ -45,7 +58,12 @@ export const useQrReader: UseQrReaderHook = ({
}

return () => {
controlsRef.current?.stop();
if (controlsRef.current === undefined) {
/** invalidate the ref as the component is unmounted */
controlsRef.current = null;
} else {
controlsRef.current?.stop();
}
};
}, []);
};