Eitan Sarikov
Eitan Sarikov

Reputation: 1

React Socket io send data to client to specific emit

I have 2 components

 const CompA = () => {
  useEffect(() => {
    socket.on("test_response", (d) => {
      debugger;
    });
    socket.emit("test", { comp: "a" });
  }, []);
  return <h1>im comp A</h1>;
};

const CompB = () => {
  useEffect(() => {
    socket.on("test_response", (d) => {
      debugger;
    });
    socket.emit("test", { comp: "b" });
  }, []);
  return <h1>im comp B</h1>;
};

Server:

io.on("connection", (socket) => {
  console.log("a user connected");
  socket.on("disconnect", (reason) => {
    console.log("user disconnected", reason);
  });
  socket.on("test", (d) => {
    socket.emit("test_response", { message: "your request is", data: d });
  });
});

it appears that CompA and CompB receiving both response from api for either request of either of them. how can I separate the response from API to be only to who emitted the event?

Upvotes: 0

Views: 76

Answers (1)

Adarsh Raj
Adarsh Raj

Reputation: 323

i think you should use this https://socket.io/docs/v4/namespaces/ namespaces allow you separate out different kind of receivers for ex you could emit like this.

socket.emit("test", { comp: "b" });

// receive test  like this

socket.on("test", (d) => {
    socket.of(d.comp).emit("test_response", { message: "your request is", data: d });
  });

//socket.of('A').emit("test_response", { message: "your request is", data: d });
//socket.of('B').emit("test_response", { message: "your request is", data: d });

and receive like this in Comp A

socket.of('A').on("test_response", (d) => {
      debugger;
    });

Upvotes: 1

Related Questions