React Native Sqlite fetch all data in Listview

2020-07-13 07:42发布

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.

2条回答
劳资没心,怎么记你
2楼-- · 2020-07-13 08:16

It works like this

record = this.state.record.slice()
                record.push(row.name)
                this.setState({ record: record })
查看更多
霸刀☆藐视天下
3楼-- · 2020-07-13 08:33

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.

查看更多
登录 后发表回答