0

weird little thing going on here. I have this working function:

import React, { useState } from "react"; 
import firebase from "firebase"; 

const firestore = firebase.firestore(); 

var userID = "xxxxxx"
const ProfilePage = () => { 
const [profileData, setProfileData] = useState(null); 

//Code to run when component mounts 
//that is when page loads 
useEffect(() => { 
firestore 
.collection("profiledata") 
.doc(userID) 
.get() 
.then((doc) => { 
setProfileData(doc.data()); 
}); 
}, []); 

return ( 
<div className="profile"> 
<h1>User</h1> 

{profileData && ( 
//if profileData exist render div 
<div> 
<p> 
First Name : {profiledata.firstname} 
Last Name : {profiledata.lastname} 
Company Name : {profiledata.companyname} 
</p> 
</div> 
)} 
</div> 
); 
}; 

and it works like a charm, displays everything on screen as it should, but only when the userID is hardcoded like so:

var userID = "xxxxxx"

and I also have this function:

 var userID = ""
firebase.auth().onAuthStateChanged((user) => {
    if(user) {
    //   console.log("profile.js " + user.uid)
    //   userID = user.uid
    userID = user.uid

      console.log("userid inside firebase auth " + user.uid)
  

    }
      })

which works to get the userID, and sets it into the global variable. I know it is working because I can display the variable on screen, but the problem is, it is now not displaying the information on screen like before... seems to only work when it is hardcoded. any solutions?

Gianluca
  • 900
  • 8
  • 27

1 Answers1

1

The problem is most likely that the userID = user.uid currently runs after the firestore.collection("profiledata").doc(userID) has run. This is because determining the user's authentication state may require a call to the server, which happens asynchronously.

The solution is to build/rebuild the query once the onAuthStateChanged fires:

var userID = ""
firebase.auth().onAuthStateChanged((user) => {
    if(user) {
        firestore 
        .collection("profiledata") 
        .doc(userID) 
        .get() 
        .then((doc) => { 
            setProfileData(doc.data()); 
        }); 
    }
})

This is an incredibly common problem for developers new to dealing with asynchronous cloud APIs, so I recommend taking some time to study it.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807