I'm trying to arrange my chats gotten from firebase into and object. I get the chats then try to arrange it into an object which contains a the chat object and the receiver.
This code arranges the chats but only does so after I have refreshed the expo app. I checked the internet and saw that it was because users and and chats are states and they had not been set by then.
useEffect(() => {
const chatsSub = onSnapshot(collection(firestore, "Chats"), querySnapshot => {
const data = []
querySnapshot.forEach((doc) => {
data.push(doc.data())
});
console.log("Chats: ", data);
setChats(data)
const list = []
chats.forEach(chat => {
if (chat.members.includes(userId)) {
chat.members.forEach(y => {
if (y !== userId) {
console.log("receiver: " y)
users.forEach(z => {
if (z.id === y) {
console.log(z)
list.push({
chat: chat,
acc: z,
user: user
})
}
})
console.log(list)
}
})
}
})
setUserChats(list)
console.log("Users Chats: " userChats)
});
}, [])
But when I try to get the users and chats at the time I'm trying to arrange the user chats. But this code does not work. It just throws an error instea
useEffect(() => {
const list = []
doc.data().chatList.forEach(chatId => {
const chatSub = onSnapshot(doc(firestore, "Chats", chatId), (doc1) => {
doc1.data().members.forEach(member => {
if (member !== userId){
const userSub = onSnapshot(doc(firestore, "Users", member), (doc2) => {
list.push({
chat: doc1.data(),
acc: doc2.data()
})
})
}
})
})
})
setUserChats(list)
}, [])
I don't know if it's because I cant have an onSnapshot inside another onSnapshot
CodePudding user response:
You can build the chat list once both the state values have been updated. Move the logic to build the chat list into an useEffect hook and add dependencies for chat and user states.
Refer the below code.
useEffect(() => {
if (chats.length && users.length) {
const list = [];
chats.forEach((chat) => {
if (chat.members.includes(userId)) {
chat.members.forEach((y) => {
if (y !== userId) {
console.log("receiver: " y);
users.forEach((z) => {
if (z.id === y) {
console.log(z);
list.push({
chat: chat,
acc: z,
user: user
});
}
});
console.log(list);
}
});
}
});
setUserChats(list);
}
}, [chats, users]);