'Why is my callback function not working everytime?

I am working on a personal project using React and Node.js, and I am linking them with a socket from Socket.io. So I have some events that are working fine, here is an exemple :

Front-end code :

const handleSubmit = (e) => {
    e.preventDefault();
    myContext.socket.emit("connectGame", pinInput, (result) => {
      if(result.code === 200){
        navigate(`/play/${result.data.pin}`); //this code is reached
      }
    });
  };

Back-end code :

  socket.on("connectGame", (pin, callback) => {
    if (pin != null) {
      const gameIndex = games.findIndex((g) => g.pin === pin);
      if (gameIndex !== -1) {
        games[gameIndex].players.push({
          socket,
          username: "",
        });
        //200
        return callback({
          code: 200,
          data: {
            error: "Game found",
            pin,
          },
        });
      }
      //404
      return callback({
        code: 404,
        data: {
          error: "Game not found",
        },
      });
    } else {
      //403
      return callback({
        code: 403,
        data: {
          error: "No PIN set",
        },
      });
    }
  });

My callback function is working perfectly there. But that is not always the case. The following code throw me an error, and I cannot explain why :

Front-end code :

useEffect(() => {
        myContext.socket.emit("createGame", id, (result) => {
           console.log(result); 
        });
    });

Back-end code :

socket.on("createGame", (pin, callback) => {
    let newGame = {
      pin,
      players: [],
      host: socket.id,
      status: 0,
      currentMusic: {},
    };
    games.push(newGame);
    //200
    return callback({
      code: 200,
      data:{
        game: newGame
      },
    });
  })

There is the error :

return callback({
           ^

TypeError: callback is not a function
    at Socket.<anonymous> (C:\dev\quiz\server.js:39:12)
    at Socket.emit (node:events:390:28)
    at Socket.emitUntyped (C:\dev\quiz\node_modules\socket.io\dist\typed-events.js:69:22)
    at C:\dev\quiz\node_modules\socket.io\dist\socket.js:466:39      
    at processTicksAndRejections (node:internal/process/task_queues:78:11)

I will be very grateful for any help. Thanks by advance.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source