'Firebase onSnapshot collection and subcollection merge with useEffect hook
hey I have data looks like this in my Firestore db
- folders
- randomkeyGenerator - has fields like the name of folder the icon etc...
- subcollection calls Tasks - it has a lot of documents and each documents have values like title etc...
- randomkeyGenerator - has fields like the name of folder the icon etc...
what I want to do is get all folders for specific user and it subcollection which the result should look like this
data = [{folderId: "randomkeyGenerator" , folderTitle: "work", folderIcon: "👍🏻", Tasks: [{},{},{},{}]}, {other folder etc....}]
here is my code with useEffect hook I did everything right but still it shows empty array or sometimes it shows only folder fields without Tasks or empty array in tasks here is the result
Array [
Object {
"Tasks": Array [],
"folderIcon": "😨",
"folderId": "3QwC21noAwmvUAVXhJfs",
"folderTitle": "Work",
},
Object {
"Tasks": Array [],
"folderIcon": "🤵🏿",
"folderId": "ewRYhuI1TGxL1EhGq5ZB",
"folderTitle": "Untitled",
},
]
here is my code:
useEffect(() => {
setLoading(true);
const subscriber = taskRef
.where("userID", "==", user.userId)
.orderBy("createdAt")
.onSnapshot((querySnapshot) => {
const queryData = [];
querySnapshot.forEach((documentSnapshot) => {
const queryObject = {
folderId: documentSnapshot.id,
folderIcon: documentSnapshot.data().Icon,
folderTitle: documentSnapshot.data().name,
Tasks: [],
};
documentSnapshot.ref
.collection("Tasks")
.where("userID", "==", user.userId)
.onSnapshot((querySnapshotTasks) => {
querySnapshotTasks.forEach((documentSnapshotTask) => {
queryObject.Tasks.push({
...documentSnapshotTask.data(),
key: documentSnapshotTask.id,
});
});
});
queryData.push(queryObject);
});
console.log(queryData);
setData(queryData);
setLoading(false);
});
return () => subscriber();
}, []);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
