javascript - How do I ensure setState is called after the Firebase query populates array? -


i new firebase , using react native. trying populate listview data firebase. see can use promises in firebase, however, seems cannot use them .on() , .once. because need listen changes, need use .on().

the challenge me comes when want ensure state set after (and after) data retrieved firebase. code below:

listen() {     var self =     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 empty view because render() called before query populates posts array. know how ensure self.setstate({}) called after query populates array?

thank help.

i'm not entirely sure mean being called empty array. reason can imagine if called when there no data yet @ location. if cause, can detect snapshot.exists():

listen() {     var self =     var currentuserid = firebase.auth().currentuser.uid     var postlist = firebase.database().ref('/users/'+currentuserid+'/postkeys')     postlist.on('value', function(snapshot) {       if (snapshot.exists()) {         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)         })       }     })   } 

if not fix problem, can set jsbin reproduces it?


Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -