My goal is that, on my Following page, I should get all the events that I created and also all events that the users that I followed created. I am trying to implement a onSnapshot for the current user, and onSnapshot for each user that the current user is following.
Here's how I did my code:
useEffect(() => {
if (user.id) {
let subscribers = [];
const mainSubscriber = db
.collection('Events')
.doc(user.id)
.collection('following')
.onSnapshot(snapshot => {
const docs = snapshot.docs.map(d => d.data());
const events = formatEvents(docs);
setItemsByUser({...itemsByUser, [user.id]: events});
});
subscribers.push(mainSubscriber);
if (users && users.length) {
for (const u of users) {
const sub = db
.collection('Events')
.doc(u.id)
.collection('followers')
.onSnapshot(snap => {
const docs = snap.docs.map(d => d.data());
const events = formatEvents(docs);
if (docs.length) {
setItemsByUser({...itemsByUser, [u.id]: events});
}
});
subscribers.push(sub);
}
}
return () => subscribers.forEach(sub => sub());
}
}, [user.id]);
But the problem im facing is that all onSnapshot starts with itemsByUser with empty object which means every setItemsByUser will only set the events of that user, i tried adding setTimeout but it didnt work. Please help me.