简体   繁体   中英

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.

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");
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM