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) => { ...@@ -58,6 +58,18 @@ io.on("connection", (socket) => {
console.log("User Joined Room: " + room); 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 }) => { ...@@ -63,10 +63,32 @@ const SingleChat = ({ fetchAgain, setFetchAgain }) => {
console.log(messages); console.log(messages);
useEffect(() => {
socket = io(ENDPOINT);
socket.emit("setup", user);
socket.on("connection", () => setSocketConnected(true));
}, []);
useEffect(() => { useEffect(() => {
fetchMessages(); fetchMessages();
selectedChatCompare = selectedChat;
}, [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) => { const sendMessage = async(event) => {
if (event.key === "Enter" && newMessage) { if (event.key === "Enter" && newMessage) {
try { try {
...@@ -90,7 +112,7 @@ const SingleChat = ({ fetchAgain, setFetchAgain }) => { ...@@ -90,7 +112,7 @@ const SingleChat = ({ fetchAgain, setFetchAgain }) => {
console.log(data); console.log(data);
socket.emit("new message", data);
setMessages([...messages, data]); setMessages([...messages, data]);
} catch (error) { } catch (error) {
toast({ toast({
...@@ -105,11 +127,7 @@ const SingleChat = ({ fetchAgain, setFetchAgain }) => { ...@@ -105,11 +127,7 @@ const SingleChat = ({ fetchAgain, setFetchAgain }) => {
} }
}; };
useEffect(() => {
socket = io(ENDPOINT);
socket.emit("setup", user);
socket.on("connection", () => setSocketConnected(true));
}, []);
const typingHandler = (e) => { const typingHandler = (e) => {
setNewMessage(e.target.value); 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