I am facing issue while implementing private messaging using socket.io in nodejs , expressjs and reactjs.
I successfully establish the socket.io connection on backend and frontend and also send message and receive message.But issue is that message is not delivering to the particular user which i select for message , mean if on one side user saim is logged in and on the other side user stephen is logged in if user saim select another user like Rob for messaging and he sent message to the rob and on other side user stephen is logged and he select user Anna for messaging then user stephen receiving that message which saim sent to the rob and same if stephen sent message to Frank on the other side user saim receiving message in the chat box stephen.
I find many solutions and apply them but still not working.I Stuck in this blocker from many days.Please any expert can help me to resolve this issue.
Thanks in advance.
Backend Code
const io = new socketIo.Server(server, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"],
credentials: true,
},
});
app.set("socketIo", io);
const onlineUsers = new Set();
io.on("connection", (socket) => {
const userId = socket.id;
if (userId) {
socket.join(userId);
console.log("A user connected with ID", socket.id);
socket.on("createNotification", (newNotification) => {
console.log("New notification ====>", newNotification);
socket.broadcast.emit("newNotification", newNotification);
});
// Listen for a user going online
socket.on("userOnline", (userId) => {
console.log("User ID online ===>", userId);
onlineUsers.add(userId);
io.emit("updateUserStatus", Array.from(onlineUsers));
});
// Listen for a user going offline
socket.on("userOffline", (userId) => {
onlineUsers.delete(userId);
io.emit("updateUserStatus", Array.from(onlineUsers));
});
socket.on("sendChatMessage", (newMessage) => {
const recipientSocketId = newMessage.receiverId;
console.log("recipientSocketId", recipientSocketId);
console.log("user socket.id ====>", userId);
if (recipientSocketId) {
console.log("New Message ====>", recipientSocketId, newMessage);
io.to(recipientSocketId).emit("receive_message", newMessage);
} else {
console.log("Message not sent to the receiver");
}
});
}
socket.on("disconnect", () => {
console.log("A user disconnected with id ", socket.id);
});
});
io.on("error", (error) => {
console.error("Socket.IO error:", error);
});
Frontend code
import React, { useState, useEffect } from "react";
import { useQuery } from "react-query";
import io from "socket.io-client";
import axios from "axios";
import { SendHorizontal } from "lucide-react";
const socket = io.connect("http://localhost:5000");
const Chat = () => {
const fetchUsers = async () => {
const response = await fetch("/api/user");
const data = await response.json();
return data;
};
const { data: users, isLoading, isError } = useQuery("users", fetchUsers);
const loginUser = JSON.parse(localStorage.getItem("user"));
const [selectedUser, setSelectedUser] = useState(null);
const [messages, setMessages] = useState([]);
const [messageText, setMessageText] = useState("");
const { data: messageData } = useQuery(
["messages", selectedUser?._id],
() => fetchMessages(selectedUser?._id, loginUser?.result?._id),
{
enabled: !!selectedUser?._id,
}
);
useEffect(() => {
if (messageData) {
setMessages(messageData);
}
}, [messageData]);
const [onlineUsers, setOnlineUsers] = useState([]); // Initialize onlineUsers state
const isUserOnline = (userId) => {
return onlineUsers.includes(userId);
};
useEffect(() => {
socket.emit("userOnline", loginUser.result._id);
return () => {
socket.emit("userOffline", loginUser.result._id);
};
}, [loginUser.result._id]);
useEffect(() => {
const updateUserStatusListener = (onlineUserIds) => {
setOnlineUsers(onlineUserIds);
};
socket.on("updateUserStatus", updateUserStatusListener);
return () => {
socket.off("updateUserStatus", updateUserStatusListener);
};
}, []);
useEffect(() => {
socket.on("receive_message", (newMessage) => {
setMessages((prevMessages) => [...prevMessages, newMessage]);
});
return () => {
socket.off("receive_message");
};
}, []);
const handleSendMessage = async (e) => {
e.preventDefault();
if (messageText.trim() !== "") {
const newMessage = {
senderId: loginUser.result._id,
receiverId: selectedUser._id,
content: messageText,
};
setMessageText("");
try {
const response = await axios.post("/api/send", newMessage);
if (response.status === 201) {
socket.emit("sendChatMessage", newMessage);
setMessages([...messages, newMessage]);
} else {
console.log("Failed to send message");
}
} catch (error) {
console.error("Error sending message:", error);
}
}
};
if (isLoading) {
return <div>Loading...</div>;
}
if (isError) {
return <div>Error fetching users</div>;
}
const filteredUsers = users.filter(
(user) => user._id !== loginUser?.result?._id
);
const fetchMessages = async (receiverId, currentUserId) => {
try {
const response = await axios.get(
`/api/messages/${currentUserId}/${receiverId}`
);
return response.data;
} catch (error) {
console.error("Error fetching messages:", error);
throw error;
}
};
return (
<div className="flex h-screen bg-gray-100">
<div className="w-1/4 bg-white p-4 overflow-y-auto">
<h2 className="text-xl text-center font-semibold mb-8">Users</h2>
<ul>
{filteredUsers.map((user) => (
<li
key={user._id}
onClick={() => setSelectedUser(user)}
className={`mb-4 border border-spacing-2 rounded-lg p-4 cursor-pointer text-xl ${
selectedUser && selectedUser._id === user._id
? "bg-blue-300"
: ""
}`}
>
{user.username}
{isUserOnline(user._id) ? (
<span className="ml-2 text-green-500">●</span>
) : (
<span className="ml-2 text-black">●</span>
)}
</li>
))}
</ul>
</div>
<div className="w-3/4 p-4 flex flex-col justify-between">
{selectedUser && (
<div>
<h2 className="text-2xl text-white bg-gray-600 p-4 text-center w-full rounded-xl font-semibold">
Chat With {selectedUser.username}
</h2>
<div className="messages mb-4 mt-2">
{loginUser.result._id &&
messages.map((message, index) => (
<div
key={index}
className={`message mt-3 ${
message.senderId === loginUser.result._id
? "sent text-right"
: "received"
}`}
>
<span
className={`${
message.senderId === loginUser.result._id
? " bg-emerald-300 "
: " bg-amber-300"
} align-middle rounded-2xl mr-1 px-2 py-1`}
>
{message.senderId === loginUser.result._id
? loginUser.result.username
.substring(0, 1)
.toUpperCase()
: selectedUser.username.substring(0, 1).toUpperCase()}
</span>
<p
className={`message-content ${
message.senderId === loginUser.result._id
? "bg-blue-500 text-white block ml"
: "bg-gray-300 text-gray-700"
} rounded-lg p-2 inline-block max-w-[70%] break-words`}
>
{message.content}
</p>
</div>
))}
</div>
</div>
)}
{selectedUser && (
<div className="message-input flex">
<input
type="text"
className="w-full border border-gray-400 rounded-md h-10 outline-none"
value={messageText}
onChange={(e) => setMessageText(e.target.value)}
placeholder="Type your message..."
onKeyPress={(e) => {
if (e.key === "Enter") {
handleSendMessage(e);
}
}}
/>
<SendHorizontal
type="submit"
onClick={(e) => handleSendMessage(e)}
className="mt-1 w-8 h-8 text-gray-600"
/>
</div>
)}
</div>
</div>
);
};
export default Chat;
Here is the screen shot of issue
Here noor select user stephen for messages and send a message to stephen but on the other tab user Amir is logged in and receive that message which noor sent to stephen
10