Commit 485734fe authored by Balasuriya D.A.M.'s avatar Balasuriya D.A.M.

Realtime Messages Front/Back

parent c80391ca
......@@ -58,6 +58,18 @@ io.on("connection", (socket) => {
console.log("User Joined Room: " + room);
});
socket.on("new message", (newMessageRecieved) => {
var chat = newMessageRecieved.chat;
if (!chat.users) return console.log("chat.users not defined");
chat.users.forEach(user => {
if (user._id == newMessageRecieved.sender._id) return;
socket.in(user._id).emit("message recieved", newMessageRecieved);
});
});
});
......
......@@ -63,10 +63,32 @@ const SingleChat = ({ fetchAgain, setFetchAgain }) => {
console.log(messages);
useEffect(() => {
socket = io(ENDPOINT);
socket.emit("setup", user);
socket.on("connection", () => setSocketConnected(true));
}, []);
useEffect(() => {
fetchMessages();
selectedChatCompare = selectedChat;
}, [selectedChat]);
useEffect(() => {
socket.on("message recieved", (newMessageRecieved) => {
if (
!selectedChatCompare ||
selectedChatCompare._id !== newMessageRecieved.chat._id
) {
//give notification
} else {
setMessages([...messages, newMessageRecieved]);
}
});
});
const sendMessage = async(event) => {
if (event.key === "Enter" && newMessage) {
try {
......@@ -90,7 +112,7 @@ const SingleChat = ({ fetchAgain, setFetchAgain }) => {
console.log(data);
socket.emit("new message", data);
setMessages([...messages, data]);
} catch (error) {
toast({
......@@ -105,11 +127,7 @@ const SingleChat = ({ fetchAgain, setFetchAgain }) => {
}
};
useEffect(() => {
socket = io(ENDPOINT);
socket.emit("setup", user);
socket.on("connection", () => setSocketConnected(true));
}, []);
const typingHandler = (e) => {
setNewMessage(e.target.value);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment