react-zxing icon indicating copy to clipboard operation
react-zxing copied to clipboard

Help with code - Show Camera - Read code - Close camera and save value

Open mDeSimone-DFactorySrl opened this issue 1 year ago • 1 comments

Hi all, i am trying to make a simple app that, when you press a button will show the camera, read a Code and then show the result. My code is:

import { useState } from 'react';
import { useZxing } from "react-zxing";

const NewRecords = () => {
    const [result, setResult] = useState("");
    const [isSectionVisible, setIsSectionVisible] = useState(false); // Initialize visibility state
  const { ref } = useZxing({
    onDecodeResult(result) {
        console.log(result.getText());
      setResult(result.getText());
    },
  });

  return (
    <>
    <button onClick={() => setIsSectionVisible(!isSectionVisible)}>
        {isSectionVisible ? "Hide" : "Show"} camera
      </button>
      {isSectionVisible && (
        <>
          <video ref={ref} />
          <p>
            <span>Last result:</span>
            <span>{result}</span>
          </p>
        </>
      )}
    </>
  );
};

export default NewRecords;

With this when i press the "Show button" the camera wont work and is it not asking for permission. If i start my code with "isSectionVisible" at true the camera is working but when i close it and reopen it will stop working. In this second case if a code is readed this onDecodeResult(result) { console.log(result.getText()); setResult(result.getText()); }, console.log will spam continusly the result.

Can someone help me with my code? Sorry for bad eng

mDeSimone-DFactorySrl avatar Jun 28 '24 15:06 mDeSimone-DFactorySrl

Need split code for 2 components:

// components/QrCodeScanner.tsx

import { useZxing } from "react-zxing";

type Props = {
  onScan: (result: string) => void;
};
const QrCodeScanner = ({ onScan }: Props) => {
  const { ref } = useZxing({
    onDecodeResult(result) {
      onScan(result.getText());
    },
  });

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

export default QrCodeScanner;

// App.tsx

import { useState } from "react";
import QrCodeScanner from "./components/QrCodeScanner";
import styles from "./App.module.css";

function App() {
  const [showScanner, setShowScanner] = useState(false);
  const [result, setResult] = useState<string>("");

  return (
    <div className={styles.App}>
      <p>
        <button onClick={() => setShowScanner((showScanner) => !showScanner)}>
          {showScanner ? "Hide scanner" : "Show scanner"}
        </button>
      </p>

      {showScanner && <QrCodeScanner onScan={setResult} />}
      <p>
        <span>Result: </span>
        <span>{result}</span>
      </p>
    </div>
  );
}

export default App;

oleg-am avatar Jan 02 '25 09:01 oleg-am