Turtle Turtle - 13 days ago 8
Javascript Question

Iterating through multiple children in firebase

I am working on a React application and would like to add an array of organizations to the state tree. Each organization can be retrieved by:

return firebase.database().ref('/organizations/' + org).once('value').then((snapshot) => {
return snapshot.val();
});


I am currently trying:

var orgs = user.organizations.map((org)=> {
return firebase.database().ref('/organizations/' + org).once('value').then((snapshot) => {
return snapshot.val();
});
});

this.setState({
organizations: orgs,
});


Which is not working because the promise is not resolved before adding to state. Does anyone have a solution?

Answer

The solution in these cases is to move the code that needs the snapshot into the callback:

var ref = firebase.database().ref('/organizations/');
var promises = user.organizations.map(org => ref.child(org).once('value'));
Promise.all(promises).then(snapshots => {
    // all snapshots have loaded
    // TODO: call this.setState() with all snapshots.
})

Let's see if this reads better:

var promises = user.organizations.map(org => {
  return firebase.database().ref('/organizations/' + org).once('value')0;
});

Promise.all(promises).then(snapshots =>
  var orgs = snapshots.map(snapshot => snapshot.val());
  this.setState({
    organizations: orgs,
  })
})