Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use sqlite with react-native?

I am working with react-native app, and now implementing persistant data storage with SQLite. I follow the documentation, but it does not work.

I stored database inside android/app/src/main/assets/test.db

There is no error, but there is nothing shown.

This is my implemented code

let SQLite = require('react-native-sqlite-storage')

class HomeScreen extends React.Component {
constructor(props) {
    super(props);
    this.state = {
      sqliteData: [],
     };
    let db = SQLite.openDatabase({name: 'test.db', createFromLocation : "~test.db", location: 'Library'}, this.openCB, this.errorCB);
    db.transaction((tx) => {
     tx.executeSql('SELECT * FROM testTable', [], (tx, results) => {
      var len = results.rows.length;
      var rows = []
        for (var i = 0; i < len.length; i++) {
          var row = results.rows.item(i);
          rows.push(row)
          console.log(row + row.userName)
        }
        this.setState({sqliteData: rows});
     }) 
    })
  }

  errorCB(err) {
    console.log("SQL Error: " + err);
  }

  successCB() {
    console.log("SQL executed fine");
  }

  openCB() {
    console.log("Database OPENED");
  }

  render(){
     return(
        <Flatlist>--showing all items--</Flatlist>
     )
  }

}
like image 484
Sras Avatar asked Dec 19 '25 22:12

Sras


1 Answers

you need to install npm install expo-sqlite and after then you need to create an SQLite database & store it your project root folder & try this code example

    import React from 'react';
import { StyleSheet, Text, View,FlatList,Alert} from 'react-native';
import { TextInput,Button,IconButton,Colors } from 'react-native-paper';
import { SQLite } from 'expo-sqlite';
const db = SQLite.openDatabase('test.db');



class UsersScreen extends React.Component 
{   

    constructor(props) {
        super(props);
        this.state = {
          FlatListItems: [],
        };
        db.transaction(tx => {
          tx.executeSql('SELECT * FROM users', [], (tx, results) => {
            var temp = [];
            for (let i = 0; i < results.rows.length; ++i) {
              temp.push(results.rows.item(i));
            }
            this.setState({
              FlatListItems: temp,
            });
          });
        });
      }


    ListViewItemSeparator = () => {
        return (
          <View style={{ height: 0.2, width: '100%', backgroundColor: '#808080' }} />
        );
      };



    render()
    {
            return(
                <View>
                <FlatList
                  data={this.state.FlatListItems}
                  ItemSeparatorComponent={this.ListViewItemSeparator}
                  keyExtractor={(item, index) => index.toString()}
                  renderItem={({ item }) => (

                    <View key={item.userid} style={{ backgroundColor: 'white', padding: 20 }}>
                      <Text>Id: {item.userid}</Text>
                      <Text>Name: {item.firstname }</Text>
                      <Text>UserName: {item.username }</Text>
                      <Text>Email: {item.email}</Text>
                      <Text>Password: {item.password}</Text>
                      <Button icon="person-add" mode="contained" style={styles.buton} onPress={() => this.props.navigation.navigate("DeleteUser",{"UserId":item.userid})}>  Delete User </Button>
                      <Button icon="person-add" mode="contained" style={styles.buton} onPress={() => this.props.navigation.navigate("EditUser",{"UserId":item.userid})}>  Edit User </Button>

                    </View>
                  )}
                />
              </View>
            );
    }

}

const styles = StyleSheet.create({
    container: {
      backgroundColor: '#fff',
    },
    textinput:{
      marginLeft:5,
      marginLeft:5,
      backgroundColor: 'transparent'
    },
    buton:{
      margin:10,
      marginBottom:10,
      backgroundColor: '#f05555'
    }  

  });

export default UsersScreen;

this code is a part of my React Native App. Happy Coding. :)

like image 185
Adeel Ahmed Baloch Avatar answered Dec 21 '25 12:12

Adeel Ahmed Baloch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!