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

injecting a variable from the configuration service into a TypeScript decorator

I am interested in setting up a scheduled task for my NestJs application to run at regular intervals. I found information on how to use intervals in the NestJs documentation. Since my application uses configuration files, I want to keep the interval value ...

Is there a way to prevent an item from being selected in a Select component when the first letter of the option is pressed?

I'm currently working with the material UI Select component and I'm attempting to create a filter within it that will only display items matching the user's input. Below is a simplified example of my current project: function App() { con ...

TypeScript: The capability to deduce or derive values for a type from a constant object literal that is nested with non-distinct keys

I'm trying to figure out a way to utilize TS/IDE to display specific literal values from a style guide object, instead of just the inferred type. Here's an example: const guide = { colors: { black: { medium: "#000000", } ...

Storing Mobx-state-tree data in NextJS for long-term persistence

I've been attempting to integrate Mobx-state-tree with NextJS, following the pattern shown in this sample project. Issue Upon user login, the user details are stored in mobx state. However, upon refreshing the page, this data disappears. I am seekin ...

How to send a dynamic URL parameter to a function in Next.js TypeScript without using implicit typing

When utilizing the useRouter function with a parameter of type string, the following error is encountered: Type 'string | string[] | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type & ...

Steps for generating a multer file using a link to an image

My current challenge involves downloading an image from a public URL, converting it into a multer file format, and then uploading it using an existing API. So far, I've experimented with axios using responseType: "blob" and responseType: "arraybuffer" ...

Encountering an error while trying to import JSON in TypeScript

I am in need of using mock JSON data to test the rendering of my front-end. import MOCK_FAQ from '../../mocks/FAQ.json'; However, when attempting to import the file, I encountered this exception: Cannot find module '../../mocks/FAQ.json&a ...

The method this.$el.querySelector does not exist

The data retrieved from the database is inserted into the input fields and submitted as a form. This data is an object that passes the value to the database. However, when I trigger this form, an error occurs. See example of the error <input id=" ...

Cannot get Typescript Module System configuration to function properly

I'm encountering an issue with my existing TypeScript project where I'm trying to change the module type to System, but despite setting it in the project properties, the compiler always outputs in AMD format (define...). It's frustrating be ...

typescriptIn React Router v5 with TypeScript, an optional URL parameter is implemented that can have an undefined

I'm currently working with react-router v5.1 and TypeScript, and I have set up the following route configurations: <Router basename="/" hashType="slash"> <Switch> <Route path="/token/:tokenName"> <TokenPag ...

Enhancing the type safety of TypeScript Generics

Uncertainty looms over me - am I committing an error, or is this all part of the plan... Within my academic domain class Collection<E> { ... } Lies a function public Insert(item: E): void { ... } I construct a specific instance of my list const ...

Exploring TypeScript Object Properties in Angular 2

How can I extract and display the ID and title of the Hero object below? The structure of the Hero interface is based on a Firebase JSON response. hero.component.ts import {Component, Input} from 'angular2/core'; import {Hero} from '../mod ...

Fetch data from a JSON file using a URL

Having trouble accessing data from a JSON file via URL. Everything seems to be in order but nothing is working, and I'm at a loss for how to troubleshoot it. service export class JsonService { public getMenuData(): Observable<any> { ...

Dealing with router parameters of an indefinite number in Angular 5: A comprehensive guide

Is there a method to efficiently handle an unknown number of router parameters in a recursive manner? For instance: We are dealing with product categories that may have subcategories, which can have their own subcategories and so on. There are a few key ...

What type should React Router props be?

For a specific scenario, I developed a custom router component that redirects if certain parameters are missing: const StateParamRoute = (props: any) => { ... return stateParam ? <Route {...props} /> : <Redirect to="/error" />; ...

Ditch the if-else ladder approach and instead, opt for implementing a strategic design

I am currently working on implementing a strategic design pattern. Here is a simple if-else ladder that I have: if(dataKeyinresponse === 'year') { bsd = new Date(moment(new Date(item['key'])).startOf('year&apos ...

Ensuring the correct type for an object's interface property value

I am currently working on defining a new interface interface SUser { ID: number; NAME: string; MAIL: string; PASSWORD: string; GENDER: number; BIRTHDATE: string; ID_FB: string; CREDIT: number; ID_REFERRAL: number; } My objective is to c ...

I am facing an issue with the Angular2 Modal Form where it only displays the data but does

Hey there, I recently started diving into Angular and I'm loving the learning process. Currently, I've managed to successfully load a form into my Modal when clicking on "viewDetails". However, as soon as I modify the Form from <form ngNoFo ...

Leveraging an intersection type that encompasses a portion of the union

Question: I am currently facing an issue with my function prop that accepts a parameter of type TypeA | TypeB. The problem arises when I try to pass in a function that takes a parameter of type Type C & Type D, where the intersection should include al ...

Angular 15 experiences trouble with child components sending strings to parent components

I am facing a challenge with my child component (filters.component.ts) as I attempt to emit a string to the parent component. Previously, I successfully achieved this with another component, but Angular seems to be hesitant when implementing an *ngFor loop ...