Reputation: 655
I am very new to react and Firebase and I really struggle with arrays and objects I'm guessing that you can't use .map
with the way my data is formatted (or type). I've looked through stack but nothing has helped (at least in my poor efforts to implement fixes).
I am trying to use .map
to map through a result from firebase but I get the error TypeError: this.state.firebasedata.map
is not a function.
getting the data:
componentWillMount(){
this.getVideosFromFirebase()
}
getVideosFromFirebase(){
var youtubeVideos = firebase.database().ref('videos/');
youtubeVideos.on('value', (snapshot) => {
const firebasedata = snapshot.val();
this.setState({firebasedata});
});
}
relevant states:
constructor(props){
super(props);
this.state = {
firebasedata: []
}
};
.map in render:
render(){
return(
<div>
{this.state.firebasedata.map((item) =>
<div key="{item}">
<p>{item.video.name}</p>
</div>
)}
</div>
);
}
Upvotes: 2
Views: 3218
Reputation: 21
For anyone coming here now, you can simply type snapshot.docs
to get an array of all the documents in the relevant collection.
As an example, if you want to get all user objects from the collection users
you can do the following:
const getAllUsers = async () => {
const usersSnapshot = await db.collection('users').get()
const allUsers = usersSnapshot.docs.map(userDoc => userDoc.data())
return allUsers
}
Upvotes: 1
Reputation: 990
As noted above Firebase snap.val() - is an object.
When you have to go through object you can also simply use for each:
for(var key in this.state.firebasedata){
<div key="{key}">
<p>{this.state.firebasedata[key].video.name}</p>
</div>
}
I also recommend creating a separate method for it, and call it in render. Hope this helps
Upvotes: 0
Reputation: 4333
This is because firebase
does not store data as arrays, but instead as objects. So the response you're getting is an object.
Firebase has no native support for arrays. If you store an array, it really gets stored as an "object" with integers as the key names.
Read this for more on why firebase stores data as objects.
To map over objects you can do something like
Object.keys(myObject).map(function(key, index) {
console.log(myObject[key])
});
Upvotes: 6