How do I shut of camera/scanner in react-native-qrcode-scanner?

Current code:

import QRCodeScanner from 'react-native-qrcode-scanner';
function ScanScreen({ navigation }) {
  return (
    <SafeAreaView style={styles.screen}>
      <QRCodeScanner reactivate={true} reactivateTimeout={3000}
        onRead={data => navigation.navigate('Third', {target:data.data})}
      />
    </SafeAreaView>
  );
}

It works, but here's what I want to do: The user can navigate between screens, one of them being a QR code scanner. While scanning, I need to debounce the scanner so it doesn't keep generating onRead events. The user could a) start a scan in the scan screen without reading a QR code and navigate manually to another screen. b) read a QR and automatically move to another screen for processing, then go back to scan again. For this reason I need to re-enable the scanner after some reasonable time. I can't just set reactivate to false because then the QR scanner is inactive until I restart the app. The problem is that when the user stays in Another screen, the QR scanner re-activates after the timeout and tries to scan when it is not desired. What I ideally would like to do is to deactivate the QR scanner while the user is not in the scan screen, and re-activate it with the above mentioned parameters whenever the user enters the scan screen. Is there any way to do this? Thanks!


Solution 1:

I had almost the same problem. The scanner does not stop scanning while showing another View (using reactivate={true}). I am using react-navigation and so I came up to following solution.

You can listen on what is happening with your view with focus and blur.

this.props.navigation.addListener('focus', () => {
    this.setState({viewFocused: true});
});

this.props.navigation.addListener('blur', () => {
    this.setState({viewFocused: false});
});

Note: you place this piece of code in componentDidMount or using React.useEffect.

Based on the state viewFocused you can render the QR Code Scanner.

this.state.viewFocused && (
    <QRCodeScanner
        onRead={onRead}
        reactivate={true}
        reactivateTimeout={2000}
    /> );

This helps me to solve my problem. To not scan while showing other views but to scan if the view is shown again. Credits to pkyeck on github.com

Solution 2:

as explained in the doc, you can do it progammatically

  <QRCodeScanner
      onRead={this.onSuccess}
      ref={(node) => { this.scanner = node }}  <-- add this
    />

and in your method (for example, in Alert or onPress button), reactivate the scanner like this:

 onPress: () => {
      this.scanner.reactivate()
    },