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

Time:10-01

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?

CodePudding user response:

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); 
});
  • Related