This is what data are stored in Firebase Realtime Database
"Users" : {
"Joe" : {
"name" : "xxx",
"email" : "xxx"
},
"Matt" : {
"name" : "xxx",
"email" : "xxx"
}
}
This is what data need in React Native Flatlist
Users : [
{
id : "Joe"
name : "xxx",
email : "xxx",
},
{
id : "Matt"
name : "xxx",
email : "xxx",
}
]
Somewhere in componentDidMount()
..
firebase.database("Users").ref().once('value').then(function(snapshot) {
var arr = _.values(snapshot.val());
this.setState({ users: JSON.stringify(arr) });
})
In render Flatlist :
<FlatList
extraData={this.props}
data={this.props.users}
keyExtractor={(item, index) => index.toString()}
renderItem={({ item }) => (
...
How can i use firebase.database().ref()
and return what it's look like the data need in flatlist?
You can try something like this:
First in my constructor
constructor(props) {
super(props);
this.state = {
arrData:[]
};
}
then fetch data from firebase
var ref = firebase.database().ref("Users"); //Here assuming 'Users' as main table of contents
ref.once('value').then(snapshot => {
// console.log(snapshot.val());
// get children as an array
var items = [];
snapshot.forEach((child) => {
items.push({
id: child.val().id,
name: child.val().name,
email: child.val().email,
phone: child.val().phone,
status: child.val().status,
user_type: child.val().user_type
});
});
this.setState({ arrData: items});
});
and now you can populate arrData
in your FlatList
or ListView
.
Hope it helps you!