I run into a little problem regarding firebase and probably something regarding async functions, Im still new to react-native and js, so I fail to resolve this error on my own.
I have following code snipped:
lastmessage = await firebase.firestore().collection("chatrooms").doc(`${chatkeys[i]}`).collection(`${chatkeys[i]}`).orderBy("counter").limit(1).get().then( querySnapshot => { return querySnapshot.docs.forEach(doc => { doc.data().value; console.log("console log inside foreach: ", doc.data().value) }) } ) console.log(lastmessage);
The firestore call and my database is alright, but the problem is within return and console.log() itself. The console.log() inside my function works perfectly and logs the wanted value inside my console – on the other side, the console.log() outside my function, right below, is not working. It just returns me “undefinded” no matter what I do. This is a big problem because Im unable to reuse this retrieved data in the next part of my code.
Can somebody maybe tell me how I could fix this? I tried already this solution but it did nothing to my code, still I got undefined back.
Advertisement
Answer
The Array.forEach
method doesn’t expect a return value from the closure.
You’re probably looking for Array.map
:
return querySnapshot.docs.map(doc => { ...
Next up, if you put curly braces around the close you pass into map
(or forEach
), you need to include a return
statement in there too. So:
return querySnapshot.docs.forEach(doc => { return doc.data().value; })
Or shorter:
return querySnapshot.docs.forEach(doc => doc.data().value);