Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native Sqlite fetch all data in Listview

I am using this library: https://github.com/andpor/react-native-sqlite-storage for my react native project.

I retrieve single row from database like this:

db.transaction((tx) => {
        tx.executeSql('SELECT * FROM user where id = 1', [], (tx, results) => {
            console.log("Query completed");

            var len = results.rows.length;
           if (len > 0) {
                let row = results.rows.item(0);
                this.setState({userName: row.name});
            }
        });
    });


return (
        <View>
            <Text>{this.state.userName}</Text>
        </View>
    )

But now i want to fetch all data from database, tell me what wrong i am doing in below code:

 db.transaction((tx) => {
        tx.executeSql('SELECT * FROM user', [], (tx, results) => {
            console.log("Query completed");

            var len = results.rows.length;
           for (let i = 0; i < len; i++) {
                let row = results.rows.item(i);
                this.setState({record: row.name});
            }
        });
    });




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

can anyone guide me how can i show database data in listview.

like image 562
DIGITAL JEDI Avatar asked Mar 12 '18 11:03

DIGITAL JEDI


Video Answer


1 Answers

Your state value for FlatList data should be an array and you are setting it to a single string every time you itterate through.

Try changing it like below

this.setState((prevState) => ({ record : prevState.record.push(row.name)}))

PS: you need to set your initial state value for record as an empty array or so.

like image 116
bennygenel Avatar answered Oct 12 '22 23:10

bennygenel