broadcast send message to sender too!! (socket.io)
Unanswered
Chub mackerel posted this in #help-forum
Chub mackerelOP
I woking on a chat app, I add this on node.js server
and my expect is when I send message from tab A to tab B, just in tab B, I see alert. But I see in both tab
frontend code
import { Server } from "socket.io";
const io = new Server(3000, { cors: "*" });
io.on("connection", (socket) => {
console.log("A user connected:", socket.id);
socket.on("send-message", ({ message }) => {
socket.broadcast.emit("recive-message", {message});
});
});
and my expect is when I send message from tab A to tab B, just in tab B, I see alert. But I see in both tab
frontend code
useEffect(() => {
socket.on("connect", () => {
setSocketId(socket.id);
});
socket.on("recive-message", ({ message, senderId }) => {
alert(message);
// setMessages((prev) => [...prev, { id: v4(), text: message, author: "bot" }]);
});
return () => {
socket.disconnect();
socket.on("disconnected", () => {
console.log("disconnected from socket");
});
};
}, []);