question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

how correct stop video in react hook

See original GitHub issue

Hello, I have in react component, when is render I want run scanner, if not stop scanning barcode.

import React, {useRef, useEffect} from 'react';
import {BrowserMultiFormatReader, BarcodeFormat} from '@zxing/browser';
import DecodeHintType from "@zxing/library/cjs/core/DecodeHintType";
import {makeStyles} from "@material-ui/core/styles";

const useStyles = makeStyles(theme => ({
    video: {
        width: '100%',
        height: '100%',
        maxHeight: '50vh',
        objectFit: 'cover',
    },
}));

export default function ScannerZxing({callback}) {
    const classes = useStyles();
    const video = useRef();
    useEffect(() => {
            const hints = new Map();
            const formats = [BarcodeFormat.QR_CODE, BarcodeFormat.CODE_128, BarcodeFormat.ITF];
            hints.set(DecodeHintType.POSSIBLE_FORMATS, formats);
            const codeReader = new BrowserMultiFormatReader(hints, {
                delayBetweenScanSuccess: 2000,
                delayBetweenScanAttempts: 600,
            });
            var controls = null;
            controls = codeReader
                .decodeFromVideoDevice(undefined, video.current, function (result, error) {
                    if (typeof result !== "undefined") {
                        callback(result); // redirect on different page and not render this
                    }
                })
            console.log(controls);

            return function cleanup() {
                console.log('clean');
                //controls.stop();
            };
    });

    return (
        <video
            className={classes.video}
            ref={video}
        ></video>
    );
}

but it now works correctly and after scan and render different page scanner still work, could you please write example in react?

Issue Analytics

  • State:open
  • Created 3 years ago
  • Comments:12 (4 by maintainers)

github_iconTop GitHub Comments

3reactions
odahcamcommented, Dec 7, 2020

Yeah, will write in a few days. Please ping me here if it takes too long.

0reactions
tuul-wqcommented, Oct 18, 2022

@mmalomo I had a similar issue only in Safari. Using qrScanner.current.stop() disabled scanning process but didn’t affect camera’s light on my laptop. Fortunately I spotted a difference in streams ids that I got from navigator.mediaDevices.getUserMedia({ video: true }) and videoRef.current.srcObject. Thus I decided to save stream from getUserMedia and use it to stop all the video tracks.

<script type="text/javascript">
    window.addEventListener('load', async () => {
      const stream = await navigator.mediaDevices.getUserMedia({ video: true });

      const codeReader = new ZXingBrowser.BrowserQRCodeReader();
      const previewElem = document.querySelector('#video');

      // undefined - takes 1st available camera
      try {
        const controls = await codeReader.decodeFromVideoDevice(undefined, previewElem, (result) => {
          console.log('scan ...');
        });

        // stop after 1.5 sec
        setTimeout(() => {
          stream.getVideoTracks().forEach(track => track.stop());
          controls.stop();
        }, 1500);
      } catch (error) {
        console.warn(error);
      }
    });
  </script>

In React I do this to stop scanning + camera’s light.

  streamRef.current.getVideoTracks().forEach((track) => track.stop());
  qrScannerControls.current.stop();
Read more comments on GitHub >

github_iconTop Results From Across the Web

how to play/pause video in React without external library?
So my first suggestion would be to consider refactoring. You can still technically do this with refs by giving your video component a...
Read more >
How to Play/Pause video or Audio in ReactJS - GeeksforGeeks
In this article, we will discuss how to turn on/turn off video or audio. We will understand how we can turn on or...
Read more >
Introducing Hooks - React
Completely opt-in. You can try Hooks in a few components without rewriting any existing code. But you don't have to learn or use...
Read more >
Player - Video-React
Methods ; play(), Play the video. ; pause(), Pause the video. ; load(), Change the video source and re-load the video ; addTextTrack(),...
Read more >
react-media-recorder - npm
react-media-recorder is a fully typed react component with render prop, or a react hook, that can be used to: Record audio/video; Record ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found