PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 22, 2022

[FIXED] When using socket.io and react, express the value comes in multiple times

 October 22, 2022     node.js, sockets     No comments   

Issue

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


Solution

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!!



Answered By - MR.Jeon
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing