Home > Blockchain >  how to get data of logged in users from Firestore with react?
how to get data of logged in users from Firestore with react?

Time:04-14

heys guys I want to get logged in user data from Firestore using react and firebase v9 but in the console I am getting data of all the users
here my code:

const usersCollectionRef = collection(db, "users");

useEffect(() => {
   onAuthStateChanged(auth, (user) => {
      if (user) {
        getDocs(usersCollectionRef, user.uid).then((snapshot) => {
          console.log(snapshot);
        });
      }
    });

  }, []);

I want to get the data of only logged in user.

CodePudding user response:

Instead of of fetching all the documents in the users collections, you can fetch a single document as long as you know the document ID. You can use doc() to create a DocumentReference to that user's document and then use getDoc() to get that:

useEffect(() => {
  onAuthStateChanged(auth, async (user) => {
    if (user) {
      const snapshot = await getDoc(doc(db, "users", user.uid))
      console.log(snapshot.data())
    }
  });
}, []);
  • Related