Turtle
Turtle

Reputation: 1389

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?

Upvotes: 1

Views: 496

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600131

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,
  })
})

Upvotes: 1

Related Questions