I'm trying to fect data from a firebase database.
However, I have subcollections so I need to first get the id of the document and then get the docs inside the subcollection :
collection --> doucments --> subcollection --> documents
I use this :
const [data, setData] = useState([]);
useEffect(() => {
const fecthData = async () => {
try {
const querySnapshot = await getDocs(collection(db, "users"))
querySnapshot.forEach((doc) => {
console.log(doc.id, "=>", doc);
var querySnap = await getDocs(collection(db, `users/${doc.id}/general`))
console.log(querySnap)
});
}catch(err) {
console.log(err)
}
};
fecthData();
}, []);
This returns the following error :
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: F:\panel_admin\src\pages\Management.js: Unexpected reserved word 'await'. (26:26)
Removing "await" does return the needed data put in a pending promise ? How can I get the data normaly like the first document ?
CodePudding user response:
Use for...of
. The problem is forEach((doc)
function is not async
.
useEffect(() => {
const fetchData = async () => {
try {
const querySnapshot = await getDocs(collection(db, "users"))
let allDocs = [];
querySnapshot.forEach((doc) => {
allDocs.push({...doc.data(), id: doc.id});
})
for (const item of allDocs) {
const querySnap = await getDocs(collection(db, `users/${item.id}/general`))
console.log(querySnap)
}
}catch(err) {
console.log(err)
}
};
fetchData();
}, []);