Client-side websocket — Create a Connect 4 online training

Now that our server is able to manage WebSockets we will be able to modify our hook / context to synchronize with the server. Rather than managing our machine on the client side, we will listen to the messages that we will receive from the server to generate a machine that will correspond to the state of our server.

socket.addEventListener('message', (event: MessageEvent) => {
  const message= JSON.parse(
  if (message.type === 'error' && message.code === ServerErrors.AuthError) {
  } else if (message.type === 'gameUpdate') {
    setMachine(makeGame(message.state, message.context))

The method send that we had will now send the events to the server rather than to the machine.

const send = useCallback<GameContextType["send"]>((event) => {
  socket?.send(JSON.stringify({type: 'gameUpdate', event: {playerId, ...event}}))
}, [playerId])

And our method can will remain unchanged as it is based on the machine system.