简体   繁体   中英

Socket.io with React and Node.js

I'm kinda new using sockets.io and I have a pretty basic question.

I have this code on the server side where I basically try to listen for the event called setName and I pass the username parameter and I emit a new event called "setNameCb" to the client side.

io.on("connection", (socket) => {
  socket.on("setName", (username) => {
    socket.emit("setNameCb", username);
  });
});

And this code on the client side where I try to pass an username when the button is clicked. After that I listen for the setNameCb event from the server side and I try to get the username value.

const setNameFunction = () => {
  socket.emit("setName", "Cristian");
};
socket.on("setNameCb", (username) => {
  alert(username);
});

return (
  <div className="App">
    <button onClick={setNameFunction}>set name</button>
  </div>
);

Alright, eveything is working, but the problem is that I get multiple alerts with the username and I just can't figure it out why that is happening.

I'd really appreciate an explanation for this one. I know it's a very basic question but that will help me to understand better the concept.

Thank you a lot!

The socket listener in react component is created on every render, if not wrapped into useEffect.

useEffect(() => {
     const setNameFunction = () => {
     socket.emit("setName", "Cristian");
   };
   socket.on("setNameCb", (username) => {
     alert(username);
   });
   }, [])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM