React Enjoyer
React Enjoyer

Reputation: 1402

How to get a single document from firestore?

According to the documentation from firebase you can get a document very simply by using get()

But for some reason in my code it always displays that there's no such document, even though it does exist, this is what I'm doing:

useEffect(() => {

    console.log(user, "This is the user UID:"+user.uid)
    const userDoc = db.collection('usuarios').doc(user.uid);
    const doc = userDoc.get();

    if (!doc.exists) {
        console.log('No such document!');
    }
    
    else {
    userDoc
    .onSnapshot(snapshot => {
      
       const tempData = [];
       snapshot.forEach((doc) => {
         
         const data = doc.data();
         tempData.push(data);
 
       });
       setUserData(tempData);
     })
    }
}, [user]);

This is what the console.log() shows:

enter image description here

This is how it looks in firebase:

enter image description here

Upvotes: 1

Views: 756

Answers (3)

DilipCoder
DilipCoder

Reputation: 578

In your code you are using the get method to fetch user data and get doesn't provide a snapshot. also, you missed that get() will return a promise so you have to handle using async-await or .then etc.

useEffect(() => {
    console.log(user, "This is the user UID:"+user.uid);
    getUser(user.uid).then(userData => {
      setUserData(userData);
    });
}, [user]);

const getUser = async (id) => {
  try {
    const user = await db.collection('usuarios').doc(id).get();
    const userData = user.data();
    return userData;
  } catch (err){
    console.log('Error during get user, No such document!');
    return  false;
}

Upvotes: 1

Tonio
Tonio

Reputation: 1782

If you're using the firebase 8 web version, the userDoc.get() returns a promise, not the document:


userDoc.get().then((doc) => {
  if (!doc.exists) {
    console.log('No such document!');
  } else {
    const tempData = [];
    const data = doc.data();
    tempData.push(data);
    setUserData(tempData)
    console.log('it worked')
  }
}).catch((error) => {
  console.log("Error getting document:", error);
});

You can get more info about promises in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises.

Upvotes: 1

Nicholas Tower
Nicholas Tower

Reputation: 85022

const doc = userDoc.get();

if (!doc.exists) {

.get returns a promise, so you're checking the .exists property on a promise, which is undefined. You will need to wait for that promise to resolve, either with .then:

userDoc.get().then(doc => {
  if (!doc.exists) {
    // etc
  }
});

Or by putting your code in an async function and awaiting the promise:

const doc = await userDoc.get();

if (!doc.exists) {
  // etc
}

Upvotes: 1

Related Questions