aboutsummaryrefslogtreecommitdiffstats
path: root/src/components/BarcodeScanner.js
blob: 15720620675d4024d0c373d2618fcc42f6ab0a3b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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;