0% found this document useful (0 votes)
11 views4 pages

SOCKET

Uploaded by

nextsaasstarter
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views4 pages

SOCKET

Uploaded by

nextsaasstarter
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

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"
}

To Send Message use

const message={
"receiverUserId": "5155ea3b-d9fa-4c57-a77d-8b45ae6ff437",
"content": "Hello Rubel"
}
socket.emit('sendMessage', message);

To read message on server

socket.on('sendMessage', async (message) => {


console.log(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) {
socket.emit("getMyConversations", { userId: user.id });
socket.on("getMyConversations", (data) => {
setConversations(data);

SOCKET.io 2
});
}
}, 1000);
}, [user, socket, isSocketConnected]);

To send and get latest message

useEffect(() => {
if (socket && user && isSocketConnected && id) {
socket.emit("getConversationHistory", {
conversationId: id,
userId: user.id,
});

socket.on("getConversationHistory", (conversations) => {


setConversationHistory(conversations);
setAllMessages(conversations.messages);
});

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

You might also like