I am currently writing a chat app using react native. In my app, I am trying to fetch data from firebase and restructure it so that it can be displayed in the flatList of the chatscreen of my app. I have written the below code to achieve the aforementioned action:
const [groupChatMessageData, setGroupChatMessageData] = useState();
const [testMessages, setTestMessages] = useState();
const groupId = props.route.params && props.route.params.chatId;
const getNewGroupMessages = async (chatId) => {
try {
const app = getFirebaseApp();
const dbRef = ref(getDatabase(app));
const messagesRef = child(dbRef, `messages/${chatId}`);
const snapshot = await get(messagesRef);
return snapshot.val();
} catch (error) {
console.log(error);
}
};
useEffect(() => {
if (!groupId) return;
const getGroupMessages = async () => {
const data = await getNewGroupMessages(groupId);
setGroupChatMessageData(data);
};
getGroupMessages();
if (groupChatMessageData) {
const groupChatMessages = [];
for (const key in groupChatMessageData) {
const message = groupChatMessageData[key];
groupChatMessages.push({
key,
...message,
});
}
setTestMessages(groupChatMessages);
} else {
return;
}
}, []);
console.log("groupChatMessageData");
console.log(groupChatMessageData);
console.log("groupChatMessages");
console.log(groupChatMessages);
console.log("testMessages");
console.log(testMessages);
The data structure of “groupChatMessageData” is as follows:
{
"-abcdefg": {
"readBy": {
" abcdefg ": [Object]
},
"sentAt": "2024-04-26T07:16:19.414Z",
"sentBy": "abc123",
"text": "Hi"
},
"-bcdefgh": {
"readBy": {
" bcdefgh ": [Object]
},
"sentAt": "2024-04-27T05:17:36.020Z",
"sentBy": " bcd234 ",
"text": "Hi"
}
}
After running the code, I expect that there would be terminal logs showing for “groupChatMessageData”, “groupChatMesages” and “testMesages”. However, it appears that only the “groupChatMessageData”can be fetched from the firebase but the data restructuring of “groupChatMessageData” to “groupChatMesages” failed. Moreover, it appears weird that the “testMessages” can sometimes be shown on the terminal log (when I commented out the “groupChatMessages”) but sometimes failed. Regardless of the aforemtnioned, the data stored in the “testMessages” can never be displayed in the flatList.