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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With