Home > other >  When using socket.io and react, express the value comes in multiple times
When using socket.io and react, express the value comes in multiple times

Time:08-30

this is client(react) code

import { io } from "socket.io-client";

const socket = io("http://localhost:8000", { transports: ["websocket"] });
const Home = () => {
  socket.emit("server");
  socket.on("server", (data) => {
    console.log(data);
  });

  return (
    <div>
      <h1>hello</h1>
    </div>
  );
};

export default Home;

And this is server(express) code

const app = require("express")();
const server = require("http").createServer(app);
const io = require("socket.io")(server, {
  cors: {
    origin: "*",
  },
});

io.on("connection", (socket) => {
  console.log("user changmin");
  socket.on("server", (data) => {
    io.emit("server", { value: Math.floor(Math.random() * 10)   1 });
  });
});

server.listen(8000);

when i see console log in chrome developer tool, log show like this


{value: 7}

{value: 7}

{value: 9}

{value: 9}

How to solve this error? Same value come twice also another value come one more time

CodePudding user response:

First I fix next.config.js like this

reactStrictMode: false,

reactStrictMode option default is true , but change to false. Also I use useEffect

  useEffect(() => {
    socket.emit("server");
    socket.on("server", (data) => {
      console.log(data);
    });
  }, []);

Like this I can see only one time value!!

  • Related