2

I'm trying do display data from Firestore database in my component.

This is my function:

const getData = async () => {
    const data = [];

    const querySnapshot = await getDocs(
      collection(databaseRef, "mK7DFNJgRAPmtvgrZh7X6AOj8cR2")
    );
    console.log(querySnapshot);
    querySnapshot.forEach((doc) => {
      console.log(doc.id, " => ", doc.data().Title);
      data.push({
        About: doc.data().About,
        Title: doc.data().Title,
        Who: doc.data().Who,
      });
    });
    setData(data);
  };

Collection ID = Current logged in User. I want to display every document. Everything works fine but insteed of passing hard-coded string here:

      collection(databaseRef, "mK7DFNJgRAPmtvgrZh7X6AOj8cR2")

I would like to pass variable where I store my UID.

Is there any way to do that?

TheRobertos
  • 27
  • 1
  • 8

1 Answers1

0

Assuming your user is logged in, you should be able to access their UID via firebase.auth().currentUser.uid. This question's answers may be useful for more information on getting the current user's ID.

With that, you should be able to do:

const querySnapshot = await getDocs(
    collection(databaseRef, firebase.auth().currentUser.uid)
);

to get the current user's documents.

https://firebase.google.com/docs/reference/js/v8/firebase.auth.Auth#currentuser

rob0rt
  • 478
  • 4
  • 7
  • I've added: `const auth = getAuth(); let UID = auth.currentUser.uid;` And then: `const querySnapshot = await getDocs(collection(databaseRef, UID));` And now I've got an ERROR: Unhandled Rejection (TypeError): Cannot read properties of null (reading 'uid') – TheRobertos Dec 29 '21 at 21:50
  • I'am using an useEffect hook to run this getData() function. Maybe there is a problem? ` useEffect(() => { getData(); }, []);` – TheRobertos Dec 29 '21 at 21:51
  • 1
    That sounds like the user isn't logged in (yet) and you may need an auth state listener as shown in the first snippet in https://firebase.google.com/docs/auth/web/manage-users#get_the_currently_signed-in_user. – Frank van Puffelen Dec 29 '21 at 21:51
  • @FrankvanPuffelen, I think he is because I've got a method to add data and everything works fine: `const addData = () => { const authentication = getAuth(); addDoc(collection(databaseRef, authentication.lastNotifiedUid), { code here })` – TheRobertos Dec 29 '21 at 21:54