Search code examples
javascriptfirebasegoogle-cloud-firestorereactjs-native

How to make my Profile name appear on my Dashboard using Firetore collection?


noob question regarding Firestore. I am new to firebase and I am creating a simple app but could not get to show the profile name or any subcollection on my dashboard the only thing showing was the email address.

Login and signup has no problem as the data are already being stored on the firestore database. only my dashboard is the problem I cannot display anything that is inside the subcollection.

Console log has no problem as well it is showing me the user ID and the subcollection list. It doesn't show on my dashboard. Here is the sample code.

     const curUser = firebase.auth().currentUser;
     const { email } = curUser;

     const dbUser =
      firebase
        .firestore()
        .collection('users')
        .doc(curUser.uid)
        .get()   
        .then(doc => {
           if (!doc.exists) {
             console.log('No such document!');
           } else {
              console.log(doc.id, doc.data());
           }
        })      

  const { firstname, lastname, bio } = dbUser;
  this.setState({ firstname, lastname, bio, email });
 };


  render() {
     return (

     <View >
              <Text>
                 {this.state.firstname} {this.state.lastname}
              </Text>

              <Text>
                 {this.state.bio}
              </Text>

              <Text>
                 {this.state.email}
              </Text>
     </View>
    )
  }
};

firstname. lastname, and bio is showing blank. I don't know if I'm doing it right. Any help would be much appreciated. Thank you in advance.


Solution

  • The get() method is asynchronous and returns a Promise.

    When this Promise is fulfilled, its result is passed to the success handler in the then() function.

    Therefore you need to do as follows:

     firebase
        .firestore()
        .collection('users')
        .doc(curUser.uid)
        .get()   
        .then(doc => {
           if (!doc.exists) {
             console.log('No such document!');
           } else {
              console.log(doc.id, doc.data());
              const { firstname, lastname, bio } = doc.data();
              this.setState({ firstname, lastname, bio, email });
           }
        })