Home > Software design >  Expo BarcodeScanner works only the first time when I post data to my server on barcode scanned
Expo BarcodeScanner works only the first time when I post data to my server on barcode scanned

Time:01-23

Expo BarcodeScanner works only the first time when I post data to my server on barcode scanned

import React, { useState, useEffect } from "react";
import { Text, View, StyleSheet, Button } from "react-native";
import { BarCodeScanner } from "expo-barcode-scanner";
import { useSnapshot } from "valtio";
import phoneState from "../store/phoneState";
import { setqrText, setqrTextFlag } from "../store/phoneState";

export default function ScannerScreen({ navigation }) {
  const [hasPermission, setHasPermission] = useState(null);
  const [scanned, setScanned] = useState(false);
  const [text, setText] = useState("Not yet scanned");
  const { qrText, qrTextFlag } = useSnapshot(phoneState);

  useEffect(() => {
    console.log("qrTexT: ", qrText);
  }, [qrText]);

  const askForCameraPermission = () => {
    (async () => {
      const { status } = await BarCodeScanner.requestPermissionsAsync();
      setHasPermission(status === "granted");
    })();
  };

  // Request Camera Permission
  useEffect(() => {
    askForCameraPermission();
  }, []);

  // What happens when we scan the bar code
  const handleBarCodeScanned = ({ type, data }) => {
    axios
      .post(`http://${localIP}:5000/api/qr/scanQr`, { data })
      .then((response) => {
        const { message } = response.data;
      })
      .catch((e) => {
        alert("ERR : ", e);
      });
  };

  // Check permissions and return the screens
  if (hasPermission === null) {
    return (
      <View style={styles.container}>
        <Text>Requesting for camera permission</Text>
      </View>
    );
  }
  if (hasPermission === false) {
    return (
      <View style={styles.container}>
        <Text style={{ margin: 10 }}>No access to camera</Text>
        <Button
          title={"Allow Camera"}
          onPress={() => askForCameraPermission()}
        />
      </View>
    );
  }

  // Return the View
  return (
    <View style={styles.container}>
      <View style={styles.barcodebox}>
        <BarCodeScanner
          onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
          style={{ height: 400, width: 400 }}
        />
      </View>
      <Text style={styles.maintext}>{text}</Text>

      {scanned && (
        <Button
          title={"Go Back"}
          onPress={() => {
            setScanned(false);
            navigation.navigate("Home");
          }}
          color='tomato'
        />
      )}
    </View>
  );
}

As you can see here, i want to send the scanned data to my server, in order to do that im using axios.post() after barcode scanned. At first try it works just fine, but afterwards it does not scan QR code. I tried to remove my axios.post() code and logged the scanned codes in the terminal, it is scanning all QR codes that i showed the camera as expected. How to change my code to prevent this happenning?

CodePudding user response:

How about toggling some kind of waiting period while the data is actually getting sent to your server via the POST in a synchronous matter to stop the scan and then reactivate it right after?

I don't have the chance to test it on an actual device and replicate it to the precise bit but I hope you'll get the gist of it:

  // What happens when we scan the bar code
  const handleBarCodeScanned = ({ type, data }) => {
    setScanned(true);
    (async () => {
      try {
        const response = await axios.post(`http://${localIP}:5000/api/qr/scanQr`, { data })
        const { message } = response.data;
        // automatically restoring scanned to keep the ball rolling on the onBarCodeScanned callback
        setScanned(false);
      } catch (e) {
        alert("ERR : ", e);
      }
    })();
  };

The Snack on the doc page also has such kind of behaviour and a warning notice is highlighted on the page itself:

Note: Passing undefined to the onBarCodeScanned prop will result in no scanning. This can be used to effectively "pause" the scanner so that it doesn't continually scan even after data has been retrieved.

  •  Tags:  
  • Related