-1

I am trying to use react native to post the data into a php api in a mobile apps. But after I successful scan the barcode it read the data but it could not post the value to the api

scanner.js

import React, { useState, useEffect,Component,onMount} from 'react';
import { Text,TextInput, View, StyleSheet, Button } from 'react-native';
import { BarCodeScanner } from 'expo-barcode-scanner';
import {useNavigation} from'@react-navigation/native';
import {StatusBar} from 'expo-status-bar';



 

  export default function Scanner () {
  
  const [hasPermission, setHasPermission] = useState(null);
  const [scanned, setScanned] = useState(false);
  const [userid, setText] = useState('Not yet scanned')
  const [currentDate, setCurrentDate] = useState('');
  const navigation = useNavigation();


  const askForCameraPermission = () => {
    (async () => {
      const { status } = await BarCodeScanner.requestPermissionsAsync();
      setHasPermission(status === 'granted');
    })()
  }

  // Request Camera Permission
  useEffect(() => {
    askForCameraPermission();
  }, []);
  
  

  Register = () => {
    this.state={
      userid:''
    }
    let userid = this.state.userid;
    

    
      let InsertAPIURL = "http://localhost/api/insert.php";

      let headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      };

      const Data={userid};

      fetch(InsertAPIURL, {
        method: 'POST',
        headers: headers,
        body: JSON.stringify(Data)
      })
      .then((response) =>response.json())
      .then((response)=>{
        alert(response[0].Message);
      })
      .catch((error) => {
        alert("Error"+error);
      })
    
  }
  

  useEffect(() => {
    var date = new Date().getDate(); //Current Date
    var month = new Date().getMonth() + 1; //Current Month
    var year = new Date().getFullYear(); //Current Year
    var hours = new Date().getHours(); //Current Hours
    var min = new Date().getMinutes(); //Current Minutes
    var sec = new Date().getSeconds(); //Current Seconds
    setCurrentDate(
      date + '/' + month + '/' + year 
      + ' ' + hours + ':' + min + ':' + sec
    );
  }, []);
  // What happens when we scan the bar code

  const handleBarCodeScanned = ({ type, data }) => {

   
    setScanned(true);
     
     
     setText(data )
     
   
  };
  

 
  // Check permissions and return the screens
  if (hasPermission === null) {
    return (
      <View style={styles.container}>
        <Text>Requesting for camera permission</Text>
      </View>)
  }
  if (hasPermission === false) {
    return (
      <View style={styles.container}>
        <Text style={{ margin: 10 }}>No access to camera</Text>
        <Button title={'Allow Camera'} onPress={() => askForCameraPermission()} />
      </View>)
  }
 
  // Return the View
  return (
     
    <View style={styles.container}>
      <View style={styles.barcodebox}>
        <BarCodeScanner
          onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
          style={{ height: 400, width: 400 }} />
      </View>
      
      <Text style={styles.maintext}>{userid + '\n'+currentDate}
    
      </Text>

      
      {
        scanned && <Button title={'Scan again?'} onPress={() => setScanned(false)} color='tomato' />
         
      }
     
      {
        scanned && <Button title={'OK'}onPress={Register}/> 
         
      }
    </View>
  );
}



const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  maintext: {
    fontSize: 16,
    margin: 20,
  },
  barcodebox: {
    alignItems: 'center',
    justifyContent: 'center',
    height: 300,
    width: 300,
    overflow: 'hidden',
    borderRadius: 30,
    backgroundColor: 'tomato'
  }
});

api php script

<?php
    $CN = mysqli_connect('localhost', 'root', '');
    $DB = mysqli_select_db($CN, 'memberdata');

    $EncodedData = file_get_contents('php://input');
    $DecodedData = json_decode($EncodedData, true);

    $userid = $DecodedData['userid'];
    

    $insertMemberData = "insert into member(user) values ('$userid')";

    $register = mysqli_query($CN, $insertMemberData);

    if ($register) 
        $Message = "Member has been registered successfully";
    else 
        $Message = "Server Error... please try latter";

    $Response[] = array("Message" => $Message);
    echo json_encode($Response);
?>

high chance the error will be in Register function and the return side

I am new to react native I hope that someone could point out my mistake or error.

jj.
  • 1
  • 2
  • Does this answer your question? [React Native Android Fetch failing on connection to local API](https://stackoverflow.com/questions/33704130/react-native-android-fetch-failing-on-connection-to-local-api) – Phil Jun 17 '22 at 01:14
  • yes after I scanned it did not prompt the network request failed error but the data still can't store into the database I think probably the error will be inside the **Register** function in the scanner.js but I can't figure out where is the problems – jj. Jun 17 '22 at 01:46
  • **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/32391315) – Dharman Jun 17 '22 at 08:18

1 Answers1

-1
  1. First, look at the console error log, what's the error

  2. Don't use fetch, try the axios library for easier data handling and clearer catch errors.

https://www.npmjs.com/package/axios

zidniryi
  • 1,212
  • 3
  • 15
  • 36