Search code examples
reactjsfirebasegoogle-cloud-firestorereactfire

where/how do I call firebase database to get currentUser data so that a user can see their own profile?


I can't quite figure out where or how to call the firebase database to show current user's data inside of a profile container.

When a user signs up, it creates a document in firebase collection 'users' that is the same as the user's unique firebase ID.

async function signup(email, password) {
    return auth.createUserWithEmailAndPassword(email, password).then((cred) => {
      return firebase
        .firestore()
        .collection("users")
        .doc(cred.user.uid)
        .set({
          age: age,
          location: location,
          bio: bio,
          name: name,
          email,
        })
        .then(() => {
          console.log("Document Added");
          return true;
        });
    });
  } 

I need to call some of the data into the profile component below, but I'm not sure how to call it or what syntax to use.

export default function Profile() {
  const { currentUser } = useAuth();
  const history = useHistory();


  
  return (

    <>
    <div className="profileCard__cardContainer">
      <ProfileCard className="card"
                  preventSwipe={["up", "down", "left", "right"]}  
      >
        <div><h2>Profile</h2></div>
        
        <div className="email"><strong>email:</strong> {currentUser.email}
        </div>
        <div className="name">
          {currentUser.doc.data(name)}
        </div>
        

      </ProfileCard>
      <Link to="/update-profile" className="updateProfile__button">
        <Button>Update Profile</Button>
      </Link>
      </div>
    </>
  );
}

I know it's probably really simple and there's probably a concept that I don't fully understand.


Solution

  • You'll need to load the document from Firestore to get the data from it. Based on the ReactFire documentation that should be with a functional component, that looks something like:

    function UserDetails() {
      const userRef = useFirestore()
        .collection('users')
        .doc(currentUser.uid);
    
      const { status, data } = useFirestoreDocData(userRef);
      // easily check the loading status
      if (status === 'loading') {
        return <p>Loading user profile...</p>;
      }
    
      return <p>User bios: {data.bio}</p>;
    }