user15690889
user15690889

Reputation: 188

socket emits multiple times to same client socketio

I am using socket.io on a separate NodeJS server and connecting a ReactJS client to it using socket.io-client.

The connection works well, until I emit messages to a room.

on my server-side I have:

const io = new Server(server, {
  cors: {
    origin: ["http://localhost:3000"],
    methods: ["GET", "POST"],
  },
});

io.on("connection", (socket) => {
  console.log(socket.id);

  socket.join("test");
 

  socket.on("newMessage", (data) => {
    console.log("new msg");
    io.to("test).emit("message", "testing");
  });

});

on React.js client:

import React from "react";
import "./App.css";
import io from "socket.io-client";
const socket = io("http://localhost:4000");

function App() {
  const newEvent = () => {
    socket.emit("newMessage", "test");
  };
  socket.on("message", () => {
    console.log("message recieved");
  });
  return (
    <div className="App">
      <button onClick={newEvent}>Emit message</button>
      <p>test</p>
    </div>
  );
}

export default App;

the socket.on("message") method on the client side runs more than once when the server issues a io.to("test).emit("message", ... )

I haven't found a way to fix this duplication issue, is there a way to make the message emit only once to the client and not multiple times?

Upvotes: 4

Views: 3389

Answers (1)

user15690889
user15690889

Reputation: 188

I found the issue.

When receiving events on the client-side, you should be using useEffect on the .on listeners when the socket changes.

for example,

useEffect(() => {
     socket.on("message", () => {
          console.log("new message")
     })
},[socket])

doing so will make sure that the listener runs once for each connected client.

Upvotes: 1

Related Questions