BarCodeScanner not loading when permissions aren't already given (functional component with hooks).

I’m trying to make all of my components in my app functional with hooks. I’ve been using the format in the code snippet below which has worked fine for me so far. The code below functions but only when permissions on the device have already been granted before using the component, allowing me to scan.
However, I can’t seem to get the barcode scanner permissions to work or the camera to start as a result. The screen stays blank and it appears no code from the component runs.

I feel like I may need to implement a useEffect Hook (and maybe even another useState to account for the change in permission state) similarly to the Expo docs example but I’m, really struggling to do it in a way that works/doesn’t involve rewriting my entire permissions method.

Any help would on what I’m missing would be hugely appreciated.

import React, { useState} from 'react';
import {View, Button, Text, StyleSheet, Alert} from 'react-native';
import { BarCodeScanner } from 'expo-barcode-scanner';
import * as Permissions from "expo-permissions";

export default function ScanBrkPrm() {
  const [scanned, setScanned] = useState(false);
  const verifyCamPermissions = async () => {
    const result = await Permissions.askAsync(Permissions.CAMERA, Permissions.CAMERA_ROLL);
    if (result.status !== 'granted') {
      Alert.alert(
        'Insufficient permissions!',
        'You need to grant camera permissions to use this app.',
        [{ text: 'Okay' }]
      );
      return false;
    }
    return true;
  };
  const handleBarCodeScanned = async () => {
    const hasPermission = await verifyCamPermissions();
    if (!hasPermission) {
      return <Text>Please grant camera access</Text>;
    }
    setScanned(true);
    alert(`Bar code with type x and data y has been scanned!`);
  };
  return (
    <View
      style={{
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'flex-end',
      }}>
      <BarCodeScanner
        onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
        style={StyleSheet.absoluteFillObject}
      />
      {scanned && (
        <Button title={'Tap to Scan Again'} onPress={() => setScanned(false)} />
      )}
    </View>
  );
}

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