aboutsummaryrefslogblamecommitdiffstats
path: root/src/components/BarcodeScanner.js
blob: 15720620675d4024d0c373d2618fcc42f6ab0a3b (plain) (tree)
1
2
3
4
5
6
7
8
9
10

                                                         
                                                






                                                           
                                                                      




























                                                                                  
                 








                                                                                  
import React, { useState, useEffect } from 'react';
import { View, Text, Button, Alert } from 'react-native';
import { CameraView, Camera } from 'expo-camera'

const BarcodeScanner = ({ onScan }) => {
  const [hasPermission, setHasPermission] = useState(null);
  const [scanned, setScanned] = useState(false);

  useEffect(() => {
    (async () => {
      const { status } = await Camera.requestCameraPermissionsAsync();
      setHasPermission(status === 'granted');
    })();
  }, []);

  const handleBarCodeScanned = ({ type, data }) => {
    setScanned(true);
    // Simulated product fetch (replace this with an actual service call)
    const product = {
      name: 'Sample Product',
      price: 29.99,
      description: 'This is a sample product description.',
      barcode: data
    };
    onScan(product);
    Alert.alert(
      "Product Scanned",
      `Do you wish to add ${product.name} to the cart?`,
      [
        { text: "Cancel", onPress: () => setScanned(false) },
        { text: "Add to Cart", onPress: () => onScan(product) },
      ]
    );
  };

  if (hasPermission === null) return <Text>Requesting camera permission...</Text>;
  if (hasPermission === false) return <Text>No access to camera</Text>;

  return (
    <View style={{ flex: 1 }}>
      <CameraView
        onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
        style={{ flex: 1 }}
      />
      {scanned && <Button title="Scan Again" onPress={() => setScanned(false)} />}
    </View>
  );
};

export default BarcodeScanner;