1

Hello All,

SQLite Table :
Table Name : Users
Column : user_id,name

We have try to display user_id and name of User detail into FlatList but I have facing issue into put users object into array and list of array object to display into FlatList.

I have show below link of stackoverflow but still I am facing issue :

React Native Sqlite fetch all data in Listview

import React, { Component } from 'react';
import { Text,
         View,
         Button,FlatList,ListItem,
         TextInput,Alert,
         StyleSheet } from 'react-native';

var SQLite = require('react-native-sqlite-storage')
var db = SQLite.openDatabase({name: 'sqliteexample.db', createFromLocation: '~sqliteexample.db'})
const count = 0;
type Props = {};
export default class HelloWorldApp extends Component<> {

  constructor(props){
      super(props)

      this.state = {
        user_id:'',
        name:'',
        record:[],
        data:{user_id:'',name:''},
        dataSource: [{user_id:'1',name:'a1'},{user_id:'1',name:'a1'},{user_id:'1',name:'a1'}],
      };

      db.transaction(function (txn) {
      txn.executeSql('SELECT * FROM Users', [], function (tx, res) {

         var len = res.rows.length;
         console.log('mylength: ' + len);

         for (let i = 0; i < len; i++) {
           console.log('mylength: ' + res.rows.item(i).name);
           this.setState({dataSource: this.state.dataSource.put(res.rows.item(i).name)});
        }
       });
      });
  }

    onPressInsert (){
      var uid = this.state.user_id;
      var uname = this.state.name;
      console.log('lengths I ' + uid + ' abc ' + uname);
      db.transaction(function (txn) {
       txn.executeSql('INSERT INTO Users (name,user_id) VALUES (:name,:user_id)', [uname,uid]);
       txn.executeSql('SELECT * FROM Users', [], function (tx, res) {
         for (let i = 0; i < res.rows.length; ++i) {
              let row = res.rows.item(i);
              console.log('Select Id a : ' + dataSource.length);
          }
          Alert.alert('Insert Id: ' + uid + ' Name: ' + uname + ' successfully');
       });
      });
    }

    onPressUpdate () {
      var uid = this.state.user_id;
      var uname = this.state.name;
      console.log('lengths U ' + uid + ' abc ' + uname);
      db.transaction(function (txn) {
        txn.executeSql('UPDATE `Users` SET  name=? WHERE user_id=?', [uname,'3']);
        txn.executeSql('SELECT * FROM Users', [], function (tx, res) {
          Alert.alert('Update Id: ' + uid + ' Name: ' + uname + ' successfully');
       });
      });
    }

    onPressDelete () {
      var uid = this.state.user_id;
      var uname = this.state.name;
      console.log('lengths D ' + uid + ' abc ');
      db.transaction(function (txn) {
       txn.executeSql('DELETE FROM `Users` WHERE492 `user_id`=?', [uid]);
       txn.executeSql('SELECT * FROM Users', [], function (tx, res) {
         Alert.alert('Delete Id: ' + uid + ' Name: ' + uname + ' successfully');
       });
      });
    }

    onPressSelect () {
      db.transaction(function (txn) {
       txn.executeSql('SELECT * FROM Users', [], function (tx, res) {
         for (let i = 0; i < res.rows.length; ++i) {
              Alert.alert('Select Id: ' + uid + ' Name: ' + uname + ' successfully');
          }
       });
      });
    }

  render() {

    return (
      <View>
      <TextInput
         style={styles.welcome}
         placeholder="Enter Id"
         editable = {true}
         value = {this.state.user_id}
         onChangeText={(text) => this.setState({user_id:text})}
         maxLength = {30}
       />
       <TextInput
               style={styles.welcome}
               value = {this.state.name}
               placeholder="Enter Full Name"
               editable = {true}
               onChangeText={(text) => this.setState({name:text})}
               maxLength = {30}
             />
         <View>
         <Button
         onPress={this.onPressInsert.bind(this)}
         title="Insert"
         color="#841584"/>
         <Button
         onPress={this.onPressUpdate.bind(this)}
         title="Update"
         color="#841584"/>
         <Button
         onPress={this.onPressDelete.bind(this)}
         title="Delete"
         color="#841584"/>
         </View>
         <FlatList
             data={this.state.dataSource}
             renderItem={({item}) => <Text> Id is :: {item.user_id} Name is :: {item.name}</Text>}
             keyExtractor={(item, index) => index+''}
            />

            <FlatList data={this.state.record}
                         keyExtractor={(x,i) => 1}
                         renderItem={ ({item}) =>
                             <ListItem><Text>{item.name}</Text></ListItem>
                         }
               />
       </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 20,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
 itemBlock: {
   flexDirection: 'row',
   paddingBottom: 5,
 },
 itemImage: {
   width: 50,
   height: 50,
   borderRadius: 25,
 },
 itemMeta: {
   marginLeft: 10,
   justifyContent: 'center',
 },
 itemName: {
   fontSize: 20,
 },
 itemLastMessage: {
   fontSize: 14,
   color: "#111",
 }
});

1 Answer 1

0

You initial dataSource is an array of object, but while reading from DB you have considered only the name. You need to put name, user_id into the array. You have used put to add data to the array, but put is not an array method, you need to replace put with push, Please consider the following snippet

db.transaction(function (txn) {
  txn.executeSql('SELECT * FROM Users', [], function (tx, res) {

     var len = res.rows.length;
     var data = [];
     console.log('mylength: ' + len);

     for (let i = 0; i < len; i++) {
       console.log('mylength: ' + res.rows.item(i).name);
       data.push({ res.rows.item(i).name,  res.rows.item(i).user_id});
     }
     this.setState({dataSource: [...this.state.dataSource, ...data]});
  });

First, data array is being populated with the result from DB, then same is updated into the state, please note, this will append the values inside dataSource. To avoid this and populate only new values into dataSource you will to need change setState statement as

this.setState({dataSource: data});

Hope this will help!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.