-1

I have this code, which returns the parents of a certain doc. console.log(doc.ref.parent.get()) I use collectionGroup to search if there is user wit email which is same as the email of the user who is logged to the app.

var nameRef = db
    .collectionGroup('Users')
    .where('email', '==', currentUser.email)

  useEffect(() => {
    nameRef.get().then((snapshot) => {
      snapshot.docs.forEach((doc) => {
        console.log(doc.ref.parent.get())
      })
    })
  }, [])

It returns a promise:

enter image description here

How to Access the segments Array in the Path in the qf in PromiseResult. I tried some object restructuring but it did not work.

radim.1
  • 99
  • 1
  • 3
  • 12
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Alon Eitan Sep 23 '20 at 09:40
  • Please share the whole relevant code snippet. What `doc`, `ref` and `parent` are already? – tmarwen Sep 23 '20 at 09:42
  • I updated the post with relevant code. – radim.1 Sep 23 '20 at 09:47
  • Thanks for the update. And why would you want to access the `segments` property? – tmarwen Sep 23 '20 at 09:59
  • Because on the segments there are all collections and docs in the main collection in which the user belongs. Simply put I want to get the docs which belong to the logged user. – radim.1 Sep 23 '20 at 10:33

1 Answers1

2

There are several problems in your code:

#1/ You don't return anything in your useEffect function.

#2/ doc.ref.parent.get() is asynchronous and will return immediately with a promise. The problem is that the forEach() loop will not wait for those promises to be fulfilled. See more explanations here. One classical solution is to use Promise.all() as shown below.

#3/ Last but not least, note that your useEffect function is asynchronous.

So, the following should do the trick:

  var nameRef = db
        .collectionGroup('Users')
        .where('email', '==', currentUser.email);

  useEffect(() => {
        return nameRef.get().then((snapshot) => {
            const promises = [];
            snapshot.docs.forEach((doc) => {
                promises.push(doc.ref.parent.get());
            });
            return Promise.all(promises);
        });
  }, []);

  // Call the function as follows, with a then() block or use the async/await keywords
  useEffect().then((results) => {   // results is an Array of DocumentSnapshots
    results.forEach((r) => {
      console.log(r.get('segments')); 
    });
  }); 
  
Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
  • Thank you for your help. I tried the code you wrote but I get _Cannot read property 'then' of undefined_ error. Seems like the .then function does not return anything. – radim.1 Sep 23 '20 at 11:08
  • 1
    I have already solved the error with object destructuring. Thank you for your time :). – radim.1 Sep 23 '20 at 11:25