blob: 73ae19af775862518d908f8a6d1e7d0340128a44 (
plain) (
tree)
|
|
import React, { useState, useEffect } from 'react';
import { View, Text, Button, Alert } from 'react-native';
import { BarCodeScanner } from 'expo-barcode-scanner';
const BarcodeScanner = ({ onScan }) => {
const [hasPermission, setHasPermission] = useState(null);
const [scanned, setScanned] = useState(false);
useEffect(() => {
(async () => {
const { status } = await BarCodeScanner.requestPermissionsAsync();
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 }}>
<BarCodeScanner
onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
style={{ flex: 1 }}
/>
{scanned && <Button title="Scan Again" onPress={() => setScanned(false)} />}
</View>
);
};
export default BarcodeScanner;
|