private messages issue in mern stack using socket.io

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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật