My structure in firestore collection looks like this
Chat Collection
"chats": {
"xyz_doc_id_1": { msg: "one", sender_id: "xyz123", timestamp: "xyz" }, //Chat from Person A
"xyz_doc_id_2": { msg: "two", sender_id: "xyz456", timestamp: "xyz" }, //Chat from Person B
"xyz_doc_id_3": { msg: "three", sender_id: "xyz123", timestamp: "xyz" }, //Chat from Person A
"xyz_doc_id_4": { msg: "four", sender_id: "xyz456", timestamp: "xyz" }, //Chat from Person B
}
User Collection
"users": {
"xyz_user_1": { uid: "xyz123", name: "Person A" },
"xyz_user_2": { uid: "xyz456", name: "Person B" },
}
I am now tasked with storing the chat data as follows
const chatData = [
{msg: "one", sender_name: "Person A"},
{msg: "two", sender_name: "Person B"},
{msg: "three", sender_name: "Person A"},
{msg: "four", sender_name: "Person B"},
]
To achieve this, I need to first retrieve the chat data to extract the user IDs for each document. Then, using these IDs, I have to fetch the corresponding user names.
This involves utilizing nested code like below
const asyncFunction = async () => {
const chatList = await db.collection("chat").orderBy("timestamp").get()
chatList.forEach((chatDoc) => {
const msg = chatDoc.data().msg // Chat Message
const sender_id = chatData.data().sender_id // Sender ID
//At this stage, the data is retrieved sequentially
//I now require each sender's name based on their SENDER ID
db.collection("users").doc(sender_id).get().then((docForName) => {
const senderName = docForName.data().name
//Here I store the message and name
setChatData((prev) => [...prev, {msg: msg, name:senderName}])
})
})
}
The Expected Output is -
msg: "one", name: "Person A", //From Person A
msg: "two", name: "Person B", //From Person B
msg: "three", name: "Person A", //From Person A
msg: "four", name: "Person B", //From Person B
However, what I actually receive is -
msg: "one", name: "Person A", //From Person A
msg: "three", name: "Person A", //From Person A
msg: "two", name: "Person B", //From Person B
msg: "four", name: "Person B", //From Person B
I have tried chaining conditions as well but the outcome remains unchanged. How can I ensure sequential order?