Functional component with hooks: BarCodeScanner's onBarCodeScanned returning undefined.

I’m trying to create an app using only functional components with hooks. It may be something I’m doing wrong that’s completely unrelated to the function component aspect but I can’t seem to get onBarCodeScanned to return the scanned value.

I’ve used the Expo Documents’ example using a class based component to test that BarCodeScanner and onBarCodeScanned(it worked fine). I then changed “class BarcodeScannerExample extends React.Component” to “function BarcodeScannerExample(props)” and changed all instances of this.state to useState().

onBarCodeScanned gets called but I’ve yet to get it to return anything other than undefined.
When I tried this as a class component it worked fine.
In the app I am trying to make a list of scanned objects and then eventually upload them to a server.
Any help would be appreciated. Here is my relevant code:

export default function ScannerScreen(props) {

const [hasCameraPermission, setHasCameraPermission] = useState(null);
const [attendeeList, setAttendeeList] = useState([]);
const [lastScannedUrl, setLastScannedUrl] = useState("");

const [scanned, setScanned] = useState(false);
const [count, setCount] = useState(0);

useEffect(() => {

_requestCameraPermission = async () => {
    const { status } = await Permissions.askAsync(Permissions.CAMERA);

_handleBarcodeScanned = ( result ) => {
    Alert.alert('Scanned!', 'press OK to continue scanning' ,[{ text: 'OK', onPress: () => { setScanned(false); }}]); 
    console.log(JSON.stringify(result)); // PRINTS UNDEFINED - passing in ({ type, data }) and trying to console.log(data + type) throws: undefined is not an object (evaluating '_ref.type')

    return (
        <View style={styles.container}>
            <View style={{flex: 8}}>
                {hasCameraPermission === null
                    ? <Text>Requesting for camera permission</Text>
                    : hasCameraPermission === false
                        ? <Text>
                            Camera permission is not granted
                        : <BarCodeScanner
                            onBarCodeScanned={ scanned ? undefined : () => _handleBarcodeScanned()}
                                height: Dimensions.get('window').height,
                                width: Dimensions.get('window').width,
            <View style={styles.footerView}>
                <Text style={{fontSize: 20 }}>{count}</Text>
                    title='Upload Scanned List'
                    onPress={() => _onUploadPress()}


Instead of this:

  onBarCodeScanned={ scanned ? undefined : () => _handleBarcodeScanned()}

Try this:

  onBarCodeScanned={ scanned ? undefined : _handleBarcodeScanned}
1 Like

:+1: Thank you, this worked.

1 Like

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.