Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I send a nested list/array through socket.emit()

The code is:

//i want to send this matrix across to server
  const [matrix, setMatrix] = useState([
    ['', '', ''],
    ['', '', ''],
    ['', '', ''],
  ]);


//fn handler whr matrix is sent to server through socket.emit
  const updateGameMatrix = (column, row, symbol) => {
    const newMatrix = [...matrix];

    if (newMatrix[row][column] === "" || newMatrix[row][column] === null) {
      newMatrix[row][column] = symbol;
      setMatrix(newMatrix);
    }

    console.log("matrix outside update_game: " , newMatrix)  //prints the array
    socket.emit("update_game", ( newMatrix ) => {
      console.log("update game matrix: ", newMatrix)  //does not print anyt?
      setPlayerTurn(false);
    });
  };

On the server side, I listen to "update_game" that was emitted:

  socket.on("update_game", (newMatrix) => {
    console.log("MATRIX FOR UPDATE_GAME: ", newMatrix)  //printed: MATRIX FOR UPDATE_GAME:  [Function (anonymous)] 
    setPlayerTurn(false)
  });
});

Why does the socket receive my matrix as an anonymous function?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Because you’re not sending the matrix – you’re using .emit() incorrectly to send data. Using a callback function with .emit() is only for when you want confirmation from the other end, not for sending data. This code will send the matrix data:

socket.emit("update_game", newMatrix);

And, this code in the client will receive it:

socket.on("update_game", (newMatrix) => {
  console.log("MATRIX FOR UPDATE_GAME: ", newMatrix); 
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading