How can I emit socket event after loading a functional component?

Viewed 59

In a React function, I need to retrieve data generated from the backend using socket.io. The problem is that I can't retrieve the data after the page is loaded. So I can't display the game graphics and the players in the game.

I tried with useEffect, also by setting a timeout to emit the 'get-data-room' event, but I didn't find any solution that works.

Thank you very much

My backend server.js code:

socket.on("get-data-room", (roomId: string) => {
  const room: RoomType | undefined = rooms.find(
    (r: { id: string }) => r.id === roomId
  );
  if (room) {
    console.log("[list data room] after loading page");
    io.sockets.in(roomId).emit("list-data-room", room); // room contains data for the game
  }
});

socket.on("update-players-in-room-client-server", (roomId: string) => {
  const room: RoomType | undefined = rooms.find(
    (r: { id: string }) => r.id === roomId
  );
  if (room) {
    io.sockets
      .in(roomId)
      .emit("update-players-in-room-server-client", room.players);
  }
});

The frontend client.js:

const io = require("socket.io-client");

export const socket = io("http://localhost:1338/", {
  transports: ["websocket"],
  secure: true,
  extraHeaders: {
    "my-custom-header": "1234", // WARN: this will be ignored in a browser
  },
});

And my game.js:

import React, { useEffect, useState } from "react";
import { socket } from "../../../client";

const Game = () => {
  const canvas = document.getElementById("canvas-game");
  const context_game = canvas.getContext("2d");

  const [width, setWidth] = useState(null);
  const [height, setHeight] = useState(null);
  const [cells, setCells] = useState(null);
  const [arrayCells, setArrayCells] = useState(null);
  const [playersInRoom, setPlayersInRoom] = useState(null);
  const [currentPlayer, setCurrentPlayer] = useState({});

  useEffect(() => {
    const splitter = window.location.pathname.split("/");
    const idRoom = splitter[splitter.length - 1];

    const canvas_game = document.getElementById("labyrinthe-back");
    const context_game = canvas_game.getContext("2d");

    socket.emit("get-data-room", idRoom);
    socket.emit("update-players-in-room-client-server", idRoom);

    socket.on("update-players-in-room-server-client", (playersInRoom) => {
      setPlayersInRoom(playersInRoom);
    });

    socket.on("list-data-room", (room) => {
      console.log("list-data-room", room);
      setWidth(room.sizeLaby);
      setHeight(room.sizeLaby);
      setCells(room.cells);
      setArrayCells(room.arrayCells);
      setPlayersInRoom(room.players);
      console.log(arrayCells);
      const currentPlayer = room.players.find(
        (p) => p.pseudo === playerSend.pseudo
      );
      if (currentPlayer) setCurrentPlayer(currentPlayer);
    });

    const intervalId = setInterval(() => {
      draw(context_game);
    }, 1000);
  }, []);
};
0 Answers
Related