I have been able to retrieve all the necessary objects, however when console.logging them they appear as separate objects and not within an array.
I then tried to place the results into an array, however since they are logged as separate objects, my array ends up having only one object.
How do I proceed further?
The code I currently have:
onAuthStateChanged(auth, (user) => {
if (user) {
const userID = user.uid
const objectDoc = query(collection(db, "objects"), where("user", "==", userID));
const getObjectDoc = async () => {
const querySnapshot = await getDocs(objectDoc);
querySnapshot.forEach((doc) => {
let objectArr = []
console.log("Objects => ", doc.data());
objectArr.push(doc.data())
console.log(objectArr)
});
}
getObjectDoc()
} else {}
})
CodePudding user response:
The QuerySnapshot
has a docs
property that'll be an array of QueryDocumentSnapshot
. You can use map()
a new array containing the data like this:
const getObjectDoc = async () => {
const querySnapshot = await getDocs(objectDoc);
const dataArr = querySnapshot.docs.map((d) => ({
id: d.id,
...d.data()
}))
console.log(dataArr)
}
For the original code, you have let objectArr = []
within the loop that'll be empty at the start of every iteration. If you move if out of the loop, that function will work too.