javascriptreact-nativereact-native-camera

how to make barcode scanner check for barcode number from database?


Is there a way to make so the barcode scanner checks for the barcode number in my local database? I've been trying to do some searches on google but there is no tutorials for something like this.


import DataBase from '../Data/DataBase';

class BarCodeReader extends Component {
  constructor(props) {
    super(props);
    this.camera = null;
    this.barcodeCodes = [];

    this.state = {
      camera: {
        type: RNCamera.Constants.Type.back,
        flashMode: RNCamera.Constants.FlashMode.auto,
      },
    };
  }

  onBarCodeRead(scanResult) {
    if (scanResult.data != null) {
      if (!this.barcodeCodes.includes(scanResult.data)) {
        this.barcodeCodes.push(scanResult.data);
        alert(scanResult.data);
      }
    }
    return;
  }

  render() {
    return (
      <View style={styles.container}>
        <RNCamera
          ref={(ref) => {
            this.camera = ref;
          }}}
          onBarCodeRead={this.onBarCodeRead.bind(this)}
        />
      </View>
    );
  }
}

const DataBase = [
  {
    name: 'text',
    company: 'text',
    extra: '7 310350 118670',
  },
];
export default DataBase;

Solution

  • import codes from '../Data/codes';
    
    class BarCodeReader extends Component {
      constructor(props) {
        super(props);
        this.camera = null;
        this.barcodeCodes = [];
    
        this.state = {
          camera: {
            type: RNCamera.Constants.Type.back,
            flashMode: RNCamera.Constants.FlashMode.auto,
          },
        };
      }
      
      validateCode(scanResult){
        const codeData = codes.find(codeMetadata => {
           return codeMetadata.id === scanResult.data 
        })
        
        if(codeData){
          alert("code valid" + codeData)
        } else {
          alert("code not found")
        }
      }
    
      onBarCodeRead(scanResult) {
        if (scanResult.data != null) {
          if (!this.barcodeCodes.includes(scanResult.data)) {
            this.barcodeCodes.push(scanResult);
            this.validateCode(scanResult)
          }
        }
        return;
      }
    
      render() {
        return (
          <View style={styles.container}>
            <RNCamera
              ref={(ref) => {
                this.camera = ref;
              }}}
              onBarCodeRead={this.onBarCodeRead.bind(this)}
            />
          </View>
        );
      }
    }
    
    const codes = [
      {
        id: "code-id-text"
        name: 'text',
        company: 'text',
        extra: '7 310350 118670',
      },