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

fixes #287 Unable to stop the camera when route changed #357

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
9 changes: 8 additions & 1 deletion src/QrReader/hooks.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { MutableRefObject, useEffect, useRef } from 'react';
import { BrowserQRCodeReader, IScannerControls } from '@zxing/browser';

import { UseQrReaderHook } from '../types';
import { StopRequestedException, UseQrReaderHook } from '../types';

import { isMediaDevicesSupported, isValidType } from './utils';

Expand All @@ -13,6 +13,7 @@ export const useQrReader: UseQrReaderHook = ({
videoId,
}) => {
const controlsRef: MutableRefObject<IScannerControls> = useRef(null);
const stopRequested = useRef(false);

useEffect(() => {
const codeReader = new BrowserQRCodeReader(null, {
Expand All @@ -32,6 +33,11 @@ export const useQrReader: UseQrReaderHook = ({
if (isValidType(video, 'constraints', 'object')) {
codeReader
.decodeFromConstraints({ video }, videoId, (result, error) => {
if (stopRequested.current) {
//Callback to parent function continuously runs after destruction of Video Element // Stream Video Tracks
//Intentionally throwing exception to step out of parent function.
throw new StopRequestedException();
}
Comment on lines +36 to +40

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have found that throwing an Exception here is unnecessary and undesirable as it leads to an uncaught runtime error. We can also stop the code reader using controls:

    if (isValidType(video, 'constraints', 'object')) {
      codeReader
-       .decodeFromConstraints({video}, videoId, (result, error) => {
+       .decodeFromConstraints({video}, videoId, (result, error, controls) => {
          if (stopRequested.current) {
-           //Callback to parent function continuously runs after destruction of Video Element // Stream Video Tracks
-           //Intentionally throwing exception to step out of parent function.
-           throw new StopRequestedException();
+           controls?.stop();
          }
          if (isValidType(onResult, 'onResult', 'function')) {
            onResult?.(result, error, codeReader);
          }
        })
        .then((controls: IScannerControls) => (controlsRef.current = controls))
        .catch((error: Error) => {
          if (isValidType(onResult, 'onResult', 'function')) {
            onResult?.(null, error, codeReader);
          }
        });
    }

if (isValidType(onResult, 'onResult', 'function')) {
onResult(result, error, codeReader);
}
Expand All @@ -48,4 +54,5 @@ export const useQrReader: UseQrReaderHook = ({
controlsRef.current?.stop();
};
}, []);
return [stopRequested];
};
26 changes: 25 additions & 1 deletion src/QrReader/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as React from 'react';
import { useEffect, useRef } from 'react';

import { styles } from './styles';
import { useQrReader } from './hooks';
Expand All @@ -16,12 +17,35 @@ export const QrReader: React.FC<QrReaderProps> = ({
onResult,
videoId,
}) => {
useQrReader({
const [stopRequested] = useQrReader({
constraints,
scanDelay,
onResult,
videoId,
});
const isUnmounting = useRef(false);

useEffect(
() => () => {
if (isUnmounting.current) {
//Stop and remove all video based tracks from video media streams
navigator.mediaDevices
.getUserMedia({
video: true,
audio: false,
})
.then((mediaStream) =>
mediaStream.getTracks().forEach((track) => {
track.stop();
mediaStream.removeTrack(track);
})
);
Comment on lines +32 to +42

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This causes an error when QrReader is conditionally rendered, because when QrReader is unmounted, no media can be found. We can handle it:

        navigator.mediaDevices
          .getUserMedia({
            video: true,
            audio: false,
          })
          .then((mediaStream) =>
            mediaStream.getTracks().forEach((track) => {
              track.stop();
              mediaStream.removeTrack(track);
            })
          )
+         .catch((error) => {
+           console.warn('Error stopping video tracks:', error);
+         });

stopRequested.current = true;
}
isUnmounting.current = true;
},
[]
);

return (
<section className={className} style={containerStyle}>
Expand Down
13 changes: 12 additions & 1 deletion src/types/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
import { BrowserQRCodeReader } from '@zxing/browser';
import { Result } from '@zxing/library';
import { Exception } from '@zxing/library';
import { MutableRefObject } from 'react';

export class StopRequestedException extends Exception {
constructor() {
super();
Object.setPrototypeOf(this, new.target.prototype);
}
}
Comment on lines +6 to +11

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can remove this class if we use controls instead of throwing an exception


export type QrReaderProps = {
/**
Expand Down Expand Up @@ -74,4 +83,6 @@ export type UseQrReaderHookProps = {
videoId?: string;
};

export type UseQrReaderHook = (props: UseQrReaderHookProps) => void;
export type UseQrReaderHook = (
props: UseQrReaderHookProps
) => [MutableRefObject<boolean>];