App "crashes" when navigating to a view with flatlist that renders data from sqlite

106 Views Asked by At

I'm a junior dev, I have a problem with an app I'm developing. I use react native, expo, and functional components. The app crashes (goes to the default image set in the app.json) when I navigate to a view that has a date picker, by default the value of the date picker should be the current date, and the date I get from the date picker should do a query to expo-sqlite (internal storage of the device) and show the results in a flatlist. The issue I'm having is that it works fine locally (testing with expo go app) but when I realease a beta build on the android store it crashes as I said before.

so I'm using:

import * as SQLite from "expo-sqlite";
import DateTimePicker from "@react-native-community/datetimepicker";


const Realizadas = ({ navigation }) => {
  const [date, setDate] = useState(new Date());
  const [show, setShow] = useState(false);
  const [msj, setMsj] = useState("");
  const [dataMarca, setDataMarca] = useState([]);
  const [placeHolder, setPlaceHolder] = useState("Select a date");

  const db = openDatabase();

  function openDatabase() {
    if (Platform.OS === "web") {
      return {
        transaction: () => {
          return {
            executeSql: () => {},
          };
        },
      };
    }
    const db = SQLite.openDatabase("myDB.db");
    return db;
  }

  useEffect(() => {
    console.log("useEffect");
    db.transaction((tx) => {
      tx.executeSql(
        "create table if not exists user(name text, lastname text, pass text);",
        [],
        (tx, result) => {
          console.log("Created!");
        },
        (tx, error) => {
          console.error("Error creating db", error);
        }
      );

      tx.executeSql(
        "create table if not exists info (id integer primary key not null, date text, type text, state text, latitude text, longitude text);",
        [],
        (tx, result) => {
          
        },
        (tx, error) => {
          console.error("Error: ", error);

        }
      );
    });

    fetchData(date);
  }, []);

  useFocusEffect(
    React.useCallback(() => {
      fetchData(date);
    }, [])
  );

  const cambia = (event, fechaDatePicker) => {
    setShow(false);
    setDate(fechaDatePicker);
    fetchData(fechaDatePicker);
  };

  const showDatepicker = () => {
    setShow(true);
  };
  function fetchData(selectedDate) {
   
    var nuevaFecha;
    if (selectedDate == null || selectedDate == "") {
      var fechaNueva = new Date();
      var fecha = fechaNueva.getDate(); //Current Date
      var month = fechaNueva.getMonth() + 1; //Current Month
      var year = fechaNueva.getFullYear(); //Current Year
      nuevaFecha =
        year +
        "-" +
        (month <= 9 ? "0" + month : month) +
        "-" +
        (fecha <= 9 ? "0" + fecha : fecha);
    } else {
      var fa = selectedDate;
      var anio = fa.getFullYear();
      var mes = fa.getMonth() + 1;
      if (mes < 10) {
        mes = "0" + mes;
      }
      var dia = fa.getDate();
      nuevaFecha = anio + "-" + mes + "-" + dia;
    }

    setPlaceHolder(nuevaFecha);
    //var query = "Select * from marcacion where estado='ENVIADO'";
    var query =
      "Select * from marcacion where fecha like '%" +
      nuevaFecha +
      "%' and estado='ENVIADO';";
    var params = [];
    db.transaction((tx) => {
      tx.executeSql(
        query,
        params,
        (tx, result) => {
          //console.log(result.rows._array);
          if (result.rows._array.length > 0) {
            setDataMarca(result.rows._array);
            console.log(dataMarca, result.rows._array);
            setMsj("");
          } else {
            setDataMarca([]);
            console.log(dataMarca);
            setMsj("No se encontraron resultados");
          }
        },
        function (tx, err) {
          //console.log(err);
          Alert.alert("Error", "No se encuentran resultados");
          setMsj("No se encontraron resultados");
          setDataMarca([]);
          console.log(dataMarca);
  
        }
      );
    });
  }



  const renderItem = useCallback(
    ({ item }) => (
      <CollapsibleView
        arrowStyling={{ size: 0 }}
        style={styles.itemPrincipal}
        title={
          <Text style={{ color: "black", fontSize: 25 }}>{item.tipo}</Text>
        }
      >
        <Text style={styles.item}>Fecha marcación: {item.fecha}</Text>
        <Text style={styles.item}>Estado de envío: {item.estado}</Text>
      </CollapsibleView>
    ),
    []
  );

  return (
    <View style={styles.viewInicio} {...panResponder.panHandlers}>
      <View style={styles.viewTop}>
        <View style={styles.viewRellenoIzquierda}></View>

        <View style={styles.viewTitulo}>
          <Text style={styles.textoTitulo}>REALIZADAS</Text>
        </View>

        <View style={styles.viewDrawer}>
          <TouchableOpacity
            style={styles.drawer}
            onPress={() => navigation.openDrawer()}
          >
            <FontAwesome5 name="bars" size={24} color="#161924" />
          </TouchableOpacity>
        </View>
      </View>

      <View style={styles.viewDatePicker}>
        <TouchableOpacity onPress={showDatepicker}>
          <View style={styles.main}>
            <Text style={styles.vacio1}></Text>
            <View style={styles.vistaCalendario}>
              <Text style={styles.textoCalendario}>{placeHolder}</Text>
            </View>
            <View style={styles.calendario}>
              <Image
                source={require("../assets/calendario.png")}
                style={styles.logo}
              />
            </View>
          </View>
        </TouchableOpacity>
      </View>

      {show && (
        <DateTimePicker
          testID="dateTimePicker"
          format="YYYY-MM-DD"
          minDate="2020-01-01"
          maxDate="2050-12-31"
          mode={"date"}
          display="inline"
          value={date}
          onChange={cambia}
          style={styles.estiloDatePicker}
        />
      )}

      <View style={styles.viewLista}>
        {dataMarca && (
          <FlatList
            data={dataMarca}
            extraData={dataMarca}
            ListEmptyComponent={
              <View style={styles.viewMensaje}>
                <View style={styles.vistaMsj}>
                  <Text style={styles.textoMsj}>{msj}</Text>
                </View>
              </View>
            }
            renderItem={renderItem}
            keyExtractor={(item) => item.fecha}
            refreshing={true}
          />
        )}
      </View>
    </View>
  );
};

export default Realizadas;

I realized there may be a lot more errors with my code but I really want to solve that crash and I cant even see any logs because it only happens in "production"

1

There are 1 best solutions below

0
Pepopig On

I fixed this by changing Flatlist to Flashlist.