I’m new to Socket IO, and I’m currently building a real time chat application with **ReactJS **and Socket IO.
Users can select from a list of conversations they already have with users to chat in real time, or they can create new conversations with new people. Here is how the system currently works:
This code is ran after a user sends a message in a chat room with another user.
// Client
socket.emit("send message", data)
// Server
// Stores connected users
var usersArr= []
//(otherUsers variable comes from data passed from client)
socket.on("send message", data => {
const otherUsers = data.users
// Map over all users in the conversation/chat, and send them the data
otherUsers.forEach(u => {
// Find user in sockets array on server
const otherUser = usersArr.find(user => user.id == u.id)
// Send to user
io.to(otherUser.socketId).emit("receive_message", messageData)
})
})
Then on the client, I have the following event to receive messages. This code below is located on the ChatScreen where users can message each other. Chat screen holds a state value determining which conversation to display and chat in
// Client (On chat screen)
// Messages between two users stored in state and displayed
const [messages, setMessages] = useState([])
// Add new message to Chat screen's state after receiving message
socket.on("receive_message", (messageData) => {
setMessages([...messages, messageData.msg])
})
// Display all messages from the chat between the users
{messages.map(m => {
return <p>{m.msg}</p>
})}
This code works fine, however there are a few issues I encountered.
Issue 1 is If the user is not currently on the chat screen, how could they view the message? What would I have to implement to perhaps show a counter on the messages icon displayed on the home screen, indicating how many unread, received messages a user has. As currently, after receiving a message, it’s appended to ChatScreen’s state. However, this isn’t possible if the user is on another page or even on the ChatScreen with a different user/conversation. Users should still have a way to know that a message has been sent. I.e a counter indicator as mentioned above.
Issue 2 is how would I go about retrieving previous messages. Messages are currently saved to MongoDB on the server. One approach could be to load the latest x amount of messages everytime a user clicks on a chat, however this means everytime a user selects a chat, they have to wait a small amount of time to retrieve the previous messages, even if no new messages have been added
An alternative to the issue above could be to initially load x amount of messages for all chats, therefore the user only fetches the previous messages (per chat) once, which is on mount. However, if new messages are added later on, the user possibly wouldn’t be able to see them, as clicking on the chat screen wouldn’t trigger a re-fetch of previous messages in this implementation.
Any suggestions? Thanks.

in the form section I have a thing like that
