Is there a way to disable the camera on React-QR-Reader after receiving the result?

My experience with react-qr-reader has been smooth for scanning QR codes, however, I'm having trouble closing the camera after it's been opened. The LED indicator of the camera remains on even when not in use.

I attempted using the getMedia functions, but they create a new instance every time which doesn't solve the issue.

Is there another method to stop the camera? Using state hasn't been effective so far.

import { useState, useEffect, useRef } from "react";
import { QrReader } from "react-qr-reader";

const ScanQrPopUp = ({ handlePopUp, walletAddress }: ScanPopUpInterface) => {
  const [address, setAddress] = useState<string>("");
  const [isRecording, setIsRecording] = useState<boolean>(true);

  useEffect(() => {
      walletAddress(address);
      setIsRecording(false)
      closeCam();
  }, [address]);

  const closeCam = async () => {
    const stream = await navigator.mediaDevices.getUserMedia({
      audio: false,
      video: true,
    });
    stream.getTracks().forEach(function (track) {
      track.stop();
      track.enabled = false;
    });
  };


  return (
      <div>
        <h1>
          Buy
        </h1>

        {isRecording && (
          <div>
            <QrReader
              onResult={(result, error) => {
                if (result) {
                  setAddress(result?.text);
                }
                if (!!error) {
                  console.log(error);
                }
              }}
              style={{ width: "100%" }}
            />
          </div>
        )}

        <p>{address}</p>
    </div>
  );
};

export default ScanQrPopUp;

Answer №1

Just insert window.location.reload()

const closeCameraFunction = async () => {
    const stream = await navigator.mediaDevices.getUserMedia({
      audio: false,
      video: true,
    });
    // Additional cleanup code goes here
    window.location.reload()
};

Answer №2

Attempt to halt the camera by using ref

import { useState, useEffect, useRef } from "react";
import { QrReader } from "react-qr-reader";

const ScanQrPopUp = ({ handlePopUp, walletAddress }: ScanPopUpInterface) => {
    const [address, setAddress] = useState<string>("");
    const [isRecording, setIsRecording] = useState<boolean>(true);
    const  ref = useRef(null);

    useEffect(() => {
        walletAddress(address);
        setIsRecording(false)
        closeCam();
    }, [address]);

    const closeCam = async () => {
        const stream = await navigator.mediaDevices.getUserMedia({
            audio: false,
            video: true,
        });
        stream.getTracks().forEach(function (track) {
            track.stop();
            track.enabled = false;
        });
        ref.current.stopCamera()
    };


    return (
        <div>
            <h1>
                Purchase
            </h1>

            {isRecording && (
                <div>
                    <QrReader
                        onResult={(result, error) => {
                            if (result) {
                            setAddress(result?.text);
                            }
                            if (!!error) {
                            console.log(error);
                            }
                        }}
                        style={{ width: "100%" }}
                        ref={ref}
                    />
                </div>
            )}

            <p>{address}</p>
        </div>
    );
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues with TypeScript Optional Parameters functionality

I am struggling with a situation involving the SampleData class and its default property prop2. class SampleData { prop1: string; prop2: {} = {}; } export default SampleData; Every time I attempt to create a new instance of SampleData without sp ...

React Type Mutation response feedback is a valuable tool for receiving input

I am facing an issue with passing the mutation success response in my code. I have a file named change-email.tsx which calls a component file updateEmail.tsx containing a mutation function. The submit function is working fine, but I cannot figure out how t ...

Using private members to create getter and setter in TypeScript

Recently, I developed a unique auto getter and setter in JavaScript which you can view here. However, I am currently unsure of how to implement this functionality in TypeScript. I am interested in creating an Object Oriented version of this feature if it ...

Casting types of objects in Angular2 using TypeScript

Trying to extract the model object from the JSON obtained through a http response call. The following JSON represents the body of the http response, { "dataType": "RWSupplier", "partyName": "Lifecare Pharmaceuticals", "partyShortName": null, "partySecon ...

Updating a route in Next.js? Make sure to remove the classList as you

Looking to remove a specific class whenever the route changes in Next.js, I've attempted the following approach: React.useEffect(() => { const activatedLink = router.query.tags const classActivated = document.querySelector('.'+activated ...

Simultaneous Activation of Hover Effects on Multiple Elements

I have an array of objects that I'm iterating over. Here is the array: const socialLinks = [ { id: 1, child: ( <> <FaLinkedin className='text-2xl' /> Linkedin </> ), hre ...

Is there a way to resolve the issue with sequelize not running 'npx sequelize-cli db:migrate' command through docker-compose.yml?

Currently encountering the following issue: Sequelize CLI [Node: 21.7.1, CLI: 6.6.2, ORM: 6.37.1] | | Loaded configuration file "database/config/config.json". | Using environment "production". | ERROR: Access denied for user 'root ...

Can we streamline a generic overloaded function's signature to make it more concise?

I have developed a streamlined Axios wrapper function that integrates zod-parsing and presents a discriminated union for improved error handling. While the implementation successfully maintains the default behavior of Axios to throw errors in certain cas ...

Exceeding the maximum number of concurrent connections with Pusher caused issues

As I work on developing a real-time chat application using the Pusher library in Next.js, I encounter an issue with multiple concurrent connections being created while exploring the website. Upon reading an article by Pusher titled Why Am I Seeing More Ch ...

What is the alternative method for importing the browser module in next.js without using dynamic imports?

const MonacoHighlighter = require("monaco-jsx-highlighter"); After encountering a "document not found" error with this import in next.js, I attempted to find an alternative solution. const Highlighter = new MonacoHighlighter(); By directly instantiating ...

What is the correct regex expression for validating decimal numbers between 1.0 and 4.5?

I'm having trouble creating an expression to validate numbers between 1.0 to 4.5 accurately. The current expression I'm using is not working as intended: /^[1-4]{0,1}(?:[.]\d{1,2})?$/ The requirement is to only allow values between 1.0 to ...

What is the best way to analyze the current pathname and route in next.js?

Currently in the process of migrating a project developed with creat-react-app to a next.js setup. Encountered an issue while trying to migrate the matchPath function from react-router-dom to achieving a similar functionality in next.js, where we compare ...

Error in Angular SSR: Build failed due to project reference without "composite" setting set to true

Currently facing an issue while developing an Angular App with SSR. When using npm run build:ssr, the following errors are displayed: ERROR in [...]/tsconfig.json [tsl] ERROR TS6306: Referenced project '[...]/tsconfig.app.json' must have se ...

Dialog box obscuring PrimeNG dropdown menu

I'm working on an Angular2 app that utilizes PrimeNG components. My issue arises when trying to include a dropdown inside a dialog box. Despite my implementation, the dropdown ends up being cut off due to the constraints of the dialog box, as visible ...

Compile a roster of service providers specializing in unit testing imports

Recently joining a new team that works with Angular, they asked me to implement unit testing on an existing project built with Angular 8. After researching the best approach, I decided to use Karma + Jasmine for testing. I set up a .spect.ts file structure ...

Solving the issue of font awesome override in nextJS

Currently, I am integrating FontAwesome into my NextJS project with Tailwind CSS. Following the official documentation, it instructs to add the given code snippet to _app.tsx file: import { config } from "@fortawesome/fontawesome-svg-core"; impor ...

Navigating the enum data model alongside other data model types in Typescript: Tips and Tricks

In my different data models, I have utilized enum types. Is it possible to compare the __typename in this scenario? enum ActivtiyCardType { Dance, ReferralTransaction, } type ActivityCardData = { __typename:ActivtiyCardType, i ...

Having difficulty bringing in personalized fonts

I've recently created a nextjs app and I'm encountering an issue - I can't seem to import custom fonts. I attempted adding ttg files and using @fontface, but the fonts aren't displaying correctly. Can someone please assist me? Below is ...

How to save HTML content in a variable for future use in Next.js

When working with Next JS, my code resembles something like this: function Test() { return ( <section> <div>Test</div> </section> ); } Now, imagine that I want to have multiple entries here, gen ...

The function 'create' is not a recognized property within the 'Completions' type

Recently, I've been experimenting with ChatGPT and have just installed the latest version 4.8.0. My current project is built on NextJS. Prior to this, I successfully completed a project using v3.something last month, but I'm encountering diffic ...