I'm pretty new to react native and I am currently developing a chat/forum application. Recently, I have been having some trouble trying to create a direct message section for my app. I don't know how to connect my database to my frontend. Here is the issue:
I use a mongodb database that consists of two collections: messages and conversations.
Each conversation has a unique Id and each message has a chatId that corresponds to the conversation that it belongs to.
In my react native app, inside a Direct Message component, I have a flatlist
that displays the different chats.
When the Direct Message component willMount()
I call an async function, getChats()
, that fetches the chats from the database that the current user is part of. The fetched chats are then set to the state.
Then, inside getChats()
, after the chats are set to the state, I have a for loop
that basically loops through the entire this.state.chats
array and then calls a function getMessages(this.state.chats[i].id)
which fetches all the messages that share the same chatIds as the chats ids. The fetched messages are then added to this.state.messages
.
Finally, a flatlist
with the props,
keyExtractor={(item)=>item._id}
data ={this.state.chats}
renderItem={({item})=>this._renderChats(item)}
extraData = {this.state}
,renders the chats.
I want to be able to show the latest messages content and sender in the chat View
, however, an error saying that the messages content is undefined.
I think this may be due to the fact that messages aren't set to the state before the chats are rendered, but I'm not sure.
How would you solve this? Would you change the frontend or the backend? Would you change both? Should I share my code to make it easier to understand the problem?
Thanks in advance.