SOCKET
SOCKET
io
Real-time Chat Application with Socket.io
model Message {
id String
authorId String
content String
}
model Conversation {
id String
participants User[]
messages Message[]
}
{
"receiverUserId": "5155ea3b-d9fa-4c57-a77d-8b45ae6ff437",
SOCKET.io 1
"content": "Hello Rubel"
}
const message={
"receiverUserId": "5155ea3b-d9fa-4c57-a77d-8b45ae6ff437",
"content": "Hello Rubel"
}
socket.emit('sendMessage', 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.
useEffect(() => {
setTimeout(() => {
if (socket && user && isSocketConnected) {
socket.emit("getMyConversations", { userId: user.id });
socket.on("getMyConversations", (data) => {
setConversations(data);
SOCKET.io 2
});
}
}, 1000);
}, [user, socket, isSocketConnected]);
useEffect(() => {
if (socket && user && isSocketConnected && id) {
socket.emit("getConversationHistory", {
conversationId: id,
userId: user.id,
});
socket.on(`newMessage-${conversationHistory.id}`, (message
setAllMessages((prevHistory) => [...prevHistory, message
});
}
return () => {
if (socket) {
socket.off("getConversationHistory");
socket.off(`newMessage-${conversationHistory.id}`);
}
};
}, [socket, id, user, isSocketConnected, conversationHistory.i
accounts
[email protected] - adviser
[email protected] - client
SOCKET.io 3
getMyConversations
sendMessage
SOCKET.io 4