Amanda K Amanda K - 1 month ago 12
Javascript Question

Setting state on multiple variables at once from firebase

I'm new to firebase and React. I've successfully retrieved user data from firebase with the following code:

firebase.auth().onAuthStateChanged(firebaseUser => {
if(firebaseUser) {
const dbRoot = firebase.database().ref().child('users').child(firebaseUser.uid);
const name = dbRoot.child('name');
const bio = dbRoot.child('bio');

name.on('value', snap => {
this.setState({
name: snap.val()
});
});

bio.on('value', snap => {
this.setState({
bio: snap.val()
});
});

} else {
console.log("not logged in");
}
});


}

This works, but I'm looking for a better way to setState on all the values (name, bio, etc) without having to create multiple setState blocks like from above, and I haven't discovered it yet. I have a lot of data to get from the user, so that code will get more cumbersome. I'd like to do something like:

this.setState({
name: snap.name.val(),
bio: snap.bio.val(),
email: snap.email.val()
});


Or whatever the best protocol is. Can someone point me in the right direction? Thanks in advance.

Answer

You don't have get the children 'name' and 'bio' separately from dbRoot:

firebase.auth().onAuthStateChanged(firebaseUser => {
  if(firebaseUser) {
    const dbRoot = firebase.database().ref().child('users').child(firebaseUser.uid);

    dbRoot.on('value', snap => {
      const user = snap.val(); // snap is a child of 'users'
      this.setState({
        name: user.name,
        bio: user.bio,
        email: user.email
      });
    });

  } else {
    console.log("not logged in");
  }
});
Comments