Home > Software design >  How to get same data each time socket event is called
How to get same data each time socket event is called

Time:05-31

I'm new at web sockets (also in socket.io). I write a simple app for experiment purposes. And, I don't understand why my event is not triggering on each click of button.

My backend in nodejs

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

    const data = {
        name: "pikachu",
    };

    socket.emit("receive_message", data);

    socket.on("disconnect", () => {
        console.log("user disconnected");
    });
});

and frontend in reactjs

function App() {
  useEffect(() => {
    socket.on("receive_message", (data) => {
      console.log(data, "zulu");
    });
  }, [socket]);

  const getRandomHero = () => {
    socket.on("connect", () => {
      console.log("connected");
    });
  };

  return (
    <div className="App">
      <button onClick={getRandomHero}>Get random hero!</button>
    </div>
  );
}

Object data I get when every time page refreshes. How can I get this data when each time I click the button?

CodePudding user response:

You would need to emit an event from the function getRandomHero, then listen for that event on the server and return something. Something like this:

Front-end:

const getRandomHero = () => {
    socket.emit('get_hero')
}

Back end:

io.on("connect", (socket) => {
    console.log(socket.id);
    socket.on('get_hero', () => {
        socket.emit('receive_message', data);
    }
}
  • Related