'How to retrieve the user's info that is currently logged in from Firestore/Firebase?

Hey guys I have a collection on Firestore users and each collection has displayName, email, and uid and trying to get the displayName of the user that is currently logged in.

At the moment the code below is fetching all the users correctly but not the specific user that logged in. The commented out code is kinda a solution that show around but I guess I am not doing it correctly. I have been trying for a while now and cant really find a way, it should be something simple but don't know what I am missing.

 const [users, setUser] = useState([])

  useEffect(() => {
    ;(async () => {
      const users: any = []
      const db = getFirestore()
      const userRef = collection(db, 'users')
      // const userName = getAuth().currentUser?.displayName
      // const userDocument = query(userRef, where('displayName', '==', userName))
      // console.log('name', userName)
      try {
        const snapshot = await getDocs(userRef)
        snapshot.docs.forEach((doc) => {
          // const { displayName } = doc.data()
          users.push({
            ...doc.data(),
            id: doc.id,
            // displayName,
          })
        })
        console.log(users)
        setUser(users)
      } catch (err: any) {
        console.log(err.message)
      }
    })()
  }, [])


Solution 1:[1]

  1. You need the logged in user's data / displayName from 'users' collection
  2. You have already connected with firebase/firestore that means you are maintaining a valid firebase config file / credentials
  3. If the above information is correct then this can be a solution for you
  • Import firebase from the firebase config file
  • Then get the current user's uid and userProfile
const uid = firebase.auth().currentUser.uid;
const currentUserProfile = firebase.firestore().collection("users").doc(uid);
  • Then you can get the required data in useEffect as required
useEffect(() => {
    currentUserProfile.get()
        .then((doc) => {
            // const currentUserInfo = doc.data();
            const currentUserDisplayName = doc.data().displayName;
            // console.log(currentUserDisplayName)
            // now you can update your state with this value from here if required 
        })
        .catch((err) => {alert("Error in displaying Name!")})

}, [])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TradeCoder