Braven
Braven

Reputation: 553

React Native Sqlite Storage: db.transaction() function is not executed

I'm working with React-native-sqlite-storage (React native CLI). And the thing is that getmysqliData dosn't excute tx.executeSql function when I query the sqlite. And I don't know why.

the whole code is this: https://gist.github.com/BravenxX/247f97c0576881616c24d197cdd137f6

About the code:

state: data: [--DATA--] .... is temporaly, this should must be replaced with the sqlite elements in getMysqliData function.

the are 2 arrays because I use them as a real time filter (it has nothing to do with sqlite btw)

const db = SQLite.openDatabase({ name: "geslub", createFromLocation: "~databases/geslub.db" });

class TablaActProgramadas extends Component{
  constructor(props){
    super(props);
    this.state={
      value: '',
      isLoading: true,
      data:[
        {'Faena': 'aDDLB', 'Planta': 'taller Titan', 'Linea': 'Kmotasú', 'Equipo': 'Caex', 'Componente': 'N/A'}
      ],
      arrayholder: [
        {'Faena': 'aDDLB', 'Planta': 'taller Titan', 'Linea': 'Kmotasú', 'Equipo': 'Caex', 'Componente': 'N/A'}
      ],
    };

  };

  async componentDidMount(){
    await  this.getMysqliData();
    console.log('TERMINO: ComponenntDIDMOUNT')
  }

  getMysqliData(){
    const sql = 'SELECT * FROM actividades_programadas';

    db.transaction((tx) => {

      //TX.EXECUTESQL is not executed!!

      tx.executeSql(sql, [], (tx, results) => {
          if(results.rows._array.length > 0){

            this.setState({
              data: results.rows_array,
              arrayholder: results.rows_array,
              isLoading: false
            })

          }else{
            Alert.alert('ERROR en la carga de datos')

          }
        });
    });

  }

  componentWillUnmount() {
    this.closeDatabase();
  }

  closeDatabase = () => {
    if (db) {
        db.close();
    } else {
        console.log("Database no estaba abierta");
    }
  }

renderHeader = () => {
  return (
      <SearchBar
        placeholder="Filtro general..."
        lightTheme
        round
        onChangeText={text => this.searchFilterFunction(text)}
        autoCorrect={false}
        value={this.state.value}
      />
  );
};

searchFilterFunction = text => {
    this.setState({
      value: text,
    });

    const newData = this.state.arrayholder.filter(item => {
      const itemData = `${item.Faena.toUpperCase()} ${item.Planta.toUpperCase()} ${item.Linea.toUpperCase()}`;
      const textData = text.toUpperCase();

      return itemData.indexOf(textData) > -1;
    });
    this.setState({
      data: newData,
    });
  };

  render(){
    if(this.state.isLoading)
      return (
          <View style={stylesLoading.container}>
                <View>
                  <ActivityIndicator size="large" color="lightblue"/>
                </View>

                <View>
                    <Text style={stylesLoading.texto}>
                        Descargando datos... 
                    </Text>
                </View>
            </View>
      )
    else
      return(
       <FlatList
          data={this.state.data}
          showsVerticalScrollIndicator={false}
          keyExtractor={(item, index) => index.toString()}
          renderItem={({item}) =>(
            <TouchableOpacity onPress={() => this.props.navigation.navigate('RealizarActProgramadas', {
              faena: `${item.Faena}`,       //ENVIAR ID DE LA ACTIVIDAD A REALIZAR
              otherParam: 'anything you want here',
            })}>

              <ListItem
                title={`Faena: ${item.Faena}`}
                subtitle={`Planta: ${item.Planta}\nLinea: ${item.Linea}`}
              />
            </TouchableOpacity>
          )}
          ItemSeparatorComponent={this.renderSeparator}
          ListHeaderComponent={this.renderHeader()}
        />
      );
  }
}

Upvotes: 2

Views: 4441

Answers (1)

Danilo Santos
Danilo Santos

Reputation: 86

I have the same issue. This ocurred because you openDasaBase is create a new database file and not use your imported file. In my case for android I needed to put de sqlite file in android/src/main/assets/www/test.db

And use this config to open:

var db = openDatabase({name: 'test.db', createFromLocation: 1}, () => {
  console.log("Database OPENED");
}, (err) => {
  console.log("SQL Error: " + err);
});

This is better described in docs https://github.com/andpor/react-native-sqlite-storage#importing-a-pre-populated-database

Upvotes: 1

Related Questions