I am new to Firebase and using it with React Native. I am trying to populate a ListView with data from Firebase. I see that I can now use Promises in Firebase, however, it seems I cannot use them with .on()
and only with .once
. Because I need to listen for changes, I need to use .on()
.
The challenge for me now comes when I want to ensure the state is set after (and only after) the data is retrieved from Firebase. My code is below:
listen() {
var self = this
var currentUserID = firebase.auth().currentUser.uid
var postList = firebase.database().ref('/users/'+currentUserID+'/postKeys')
postList.on('value', function(snapshot) {
var posts = []
snapshot.forEach((child)=> {
var postID = child.val().postID
var postRef = firebase.database().ref('posts/'+postID)
postRef.orderByChild('sortedDateInMilliseconds').on('value', function(postSnap) {
posts.push(postSnap.val())
})
})
self.setState({
postCount:posts.length,
dataSource:self.state.dataSource.cloneWithRows(posts)
})
})
}
The result is that I initially get an empty view because the render()
is called before the query populates the posts array. Does anyone know how to ensure that the self.setState({})
is called after the query populates the array?
Thank you very much for your help.