SOCKET.
io
Real-time Chat Application with [Link]
model Message {
id String
authorId String
content String
}
model Conversation {
id String
participants User[]
messages Message[]
}
{
"receiverUserId": "5155ea3b-d9fa-4c57-a77d-8b45ae6ff437",
[Link] 1
"content": "Hello Rubel"
}
To Send Message use
const message={
"receiverUserId": "5155ea3b-d9fa-4c57-a77d-8b45ae6ff437",
"content": "Hello Rubel"
}
[Link]('sendMessage', message);
To read message on server
[Link]('sendMessage', async (message) => {
[Link](message)
}
How to config
Create a context and wrap the whole app or the chatting component or the page
also create a hook inside the context so that you can use the socket whenever you
need it.
To get the conversation History
useEffect(() => {
setTimeout(() => {
if (socket && user && isSocketConnected) {
[Link]("getMyConversations", { userId: [Link] });
[Link]("getMyConversations", (data) => {
setConversations(data);
[Link] 2
});
}
}, 1000);
}, [user, socket, isSocketConnected]);
To send and get latest message
useEffect(() => {
if (socket && user && isSocketConnected && id) {
[Link]("getConversationHistory", {
conversationId: id,
userId: [Link],
});
[Link]("getConversationHistory", (conversations) => {
setConversationHistory(conversations);
setAllMessages([Link]);
});
[Link](`newMessage-${[Link]}`, (message
setAllMessages((prevHistory) => [...prevHistory, message
});
}
return () => {
if (socket) {
[Link]("getConversationHistory");
[Link](`newMessage-${[Link]}`);
}
};
}, [socket, id, user, isSocketConnected, conversationHistory.i
accounts
pedro@[Link] - adviser
jack@[Link] - client
[Link] 3
getMyConversations
sendMessage
[Link] 4