Home > Mobile >  How to get a single document from firestore?
How to get a single document from firestore?

Time:10-17

According to the documentation from firebase you can get a document very simply by using enter image description here

This is how it looks in firebase:

enter image description here

CodePudding user response:

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
}

CodePudding user response:

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.

CodePudding user response:

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;
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related