El1Harolds
El1Harolds

Reputation: 11

My expo-sqlite database is not storing my values

I am having a problem inserting my data into my sqlite database in expo. I have used every available technique I know, it just fails me.

I have already created the database in my App.js file, Now I am collecting the information from a pins variable and sending them to my database (PHP). Point is, I want to be able to save them in my SQLite database too in react-native so I can compare for data congruence.

The data is flying over to PHP, but it's not entering SQLITE. Here is my code:

import React, { useState, useRef, useEffect } from 'react';
import { View, Text, TextInput, StyleSheet, TouchableOpacity, Button, SafeAreaView, Alert } from 'react-native';
import CheckBox from 'react-native-check-box';
import LoginStyle from './resources/styles/LoginStyle';
import axios from 'axios';
import AsyncStorage from "@react-native-async-storage/async-storage";
import * as SQLite from 'expo-sqlite/legacy';
import DbResources from "./resources/DbResources";
import { useNavigation } from '@react-navigation/native';



const db = SQLite.openDatabase("atlas.db");

/*
ALGORITHM
- First Check to make sure there is not already a user registered in the database.
  * If there is, you should direct the person to the dashboard.
  * else:
    - Check if there is a phone number sent from the previous screen. Honestly, this doesn't have to be in the local storage, it can be passed as a prop.
      * If there is, then use it as a registrations criteria, if there isn't the redirect the person to the previous state.

- In the event where there is no user in the database, you may just have to create one from the PIN and the phone number.
  When you must have done this, save the information and send it back to the database.
*/ 


const CreatePinScreen = ({route}) => {
  const navigation = useNavigation();
  const [pin, setPin] = useState(['', '', '', '']);
  const [isChecked, setIsChecked] = useState(false);
  const [pinSet, setPinSet] = useState(false);
  const [pinConfirm, setPinConfirm] = useState(['', '', '', '']);
  const [accountAvailable, setAccountAvailable] = useState(false);
  // const [phoneNumber, setPhoneNumber] = useState("");
  const {phoneNumber} = route.params;
  const [res, fetchDBR] = useState(null);
  const [userData, setUserData] = useState({});

  const inputs = useRef([]);
  const inputsConfirm = useRef([]);


  // CHECK FOR EXISTING USER
  const CheckExisting = () =>{

    db.transaction(tx => {
      tx.executeSql(
        `SELECT * FROM atlas_user_info;`,
        [],
        (_, { rows }) => {
          const rowsArray = rows._array;
          const quantity = rowsArray.length;
          console.log("All rows in atlas_user_info:", rowsArray);
          console.log("Quantity of items:", quantity);

          if(rowsArray.length > 0){
            setAccountAvailable(true);
          }
        },
        (_, error) => {
          console.error("Error selecting rows: ", error);
        }
      );
    });

  }



  React.useEffect(()=>{
      CheckExisting();

      // SEND TO DASHBOARD IF THERE IS AN ACCOUNT
      if(accountAvailable == true){
        navigation.navigate("Authenticated");
      }
  }, []);

  const handleChange = (text, index) => {
    const newPin = [...pin];
    newPin[index] = text;
    setPin(newPin);

    // Automatically focus next input
    if (text && index < inputs.current.length - 1) {
      inputs.current[index + 1].focus();
    }else{
      setPinSet(true);
    }
  };

useEffect(()=>{
    const getRes = async()=>{
      // const res = await DbResources("drop");
      if(res != 0){
        // fetchDBR(res);
        // console.log(res);
      }
    }
    getRes();
}, []);


  const handleKeyPress = (e, index) => {
    if (e.nativeEvent.key === 'Backspace' && pin[index] === '' && index > 0) {
      inputs.current[index - 1].focus();
    }
  };


  const handleChangeConfirm = (text, index) => {
    const newPinC = [...pinConfirm];
    newPinC[index] = text;
    setPinConfirm(newPinC);

    // Automatically focus next input
    if (text && index < inputsConfirm.current.length - 1) {
      inputsConfirm.current[index + 1].focus();
    }else{
      setPinSet(true);
    }
  };


  const handleKeyPressConfirm = (e, index) => {
    if (e.nativeEvent.key === 'Backspace' && pin[index] === '' && index > 0) {
      inputsConfirm.current[index - 1].focus();
    }
  };


const deleteDatabase = async () => {
  try {
    await SQLite.deleteDatabaseAsync("atlasdb.db");
    console.log('Database deleted successfully');
  } catch (error) {
    console.error('Failed to delete database:', error);
  }
};



useEffect(()=>{

  const continueOps = (rsData) =>{
    const db = SQLite.openDatabase('atlas.db');
  
    db.transaction(tx => {
      tx.executeSql(
        `SELECT * FROM atlas_user_info WHERE user_ac_token = ?;`,
        [rsData.user_ac_token],
        (_, { rows }) => {
          console.log("All rows in atlas_user_info:", rows._array);
          if(rows._array.length > 0){
            navigation.navigate("Authenticated");
          }else{
            console.log("Something happened")
          }
  
          console.log(`Total selections: `, rows._array);
        },
        (_, error) => {
          console.error("Error selecting rows: ", error);
        }
      );
    });
  };


  const saveAccountInfo = () =>{
    console.log(userData.pp_view);
  // const db = SQLite.openDatabase('atlas.db');
  // console.log(db);
  let ppView =  userData.pp_view;
  let ppManage = userData.pp_manage;
  let cbView = userData.cb_view;
  let cbManage = userData.cb_manage;
  let ivView = userData.iv_view;
  let ivManage = userData.iv_manage;
  let invView = userData.inv_view;
  let invManage = userData.inv_manage;
  // console.log(db);
  db.transaction(tx => {
    tx.executeSql(
      `INSERT INTO atlas_user_info 
      (user_db_id, user_names, user_ac_token, user_ac_status, pp_view, 
      pp_manage, cb_view, cb_manage, iv_view, iv_manage, inv_view, inv_manage) 
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        rsData.user_id,
        '',
        rsData.user_token,
        '',
        ppView,
        ppManage,
        cbView,
        cbManage,
        ivView,
        ivManage,
        invView,
        invManage
      ],
      [],
      () => {
        console.log("Table created successfully");
        // Query to list all tables
        tx.executeSql(
          `SELECT * FROM atlas_user_info`, null,
          (txObj, resultSet) => console.log(resultSet.rows._array),
          (txObj, error) =>console.log(error)
        );
      }
    );
  });

  console.log('Why are we not getting to this point?');
  continueOps(userData);

      
    // navigation.navigate("Authenticated");

  };
  if(Object.entries(userData).length > 0){
    saveAccountInfo();
  }
}, [userData]);

  const SignupUser = async ()=>{

    const p1 = pin.join('');
    const p1String = p1.toString();

    const p2 = pinConfirm.join('');
    const p2String = p2.toString();

    if(p1 == ""){
      Alert.alert('Please set your pin');
    }else{
      if(p1 != p2){
        Alert.alert("Your Pins Do not match");
      }else{
        try{
            let mode = "signup";
            let priv = 'manager';
            const dataToSend = {
              'user_phone_number' : phoneNumber,
              'user_pin' : p1,
              'user_priv' : priv,
              'mode': mode
            };
          const response = await axios.post('http://192.168.0.138/atlasbackend/apis/auth_api.php', dataToSend);
          if(response != "0" && response.data!=0){
            console.log(`data is: ${response.data}`);
            setUserData(response.data);
            
          }else{
            console.log("Data is just zero");
          }
          // console.log(response.data);

        }catch(error){
          console.error("An error happened: " + error);
        }
      }

    }
  }




/*







*/


};



export default CreatePinScreen;                    
                      
                      
  

take particular look at the SaveAccountInfo function that uses the state variable - > userData. this is where the problem is. Thank you for your help.

I tried placing the code in the useEffect hook hoping to get better outcomes, but to no avail. I have tried using openDatabaseAsync and openDatabaseSync, all to no avail. So I reverted back to this method. The database tables are being created quite alright, but data is not entering.

Upvotes: 1

Views: 137

Answers (0)

Related Questions