Chapter 7 - Draw simultaneously on multiple windows¶
In the previous chapter, you were able to validate your frontend and your backend can communicate.
In this chapter, you'll update the WebSocket provider to send the drawing data to the WebSocket gateway. This will allow you to draw simultaneously on multiple windows!
import{createContext,useContext,useEffect,useMemo}from"react";import{Socket,io}from"socket.io-client";import{useLines}from"@/components/line-provider";import{Point}from"@/types/point";typeState={// (1)!emitFirstPointFromPlayer:Function,emitPointFromPlayer:Function};constWebSocketContext=createContext<State|undefined>(undefined);functionWebSocketProvider({children}:{children:React.ReactNode}):JSX.Element{constsocket:Socket=useMemo(()=>io("localhost:4000",{autoConnect:false}),[]);const{dispatch}=useLines();useEffect(()=>{if(!socket.connected){socket.connect();}return()=>{socket.close();};},[socket]);useEffect(()=>{// (2)!if(!socket)return;socket.on("FIRST_POINT_TO_PLAYERS",(point:Point)=>{// (3)!dispatch({type:"ADD_FIRST_POINT",point:point});});socket.on("POINT_TO_PLAYERS",(point:Point)=>{// (4)!dispatch({type:"ADD_POINT",point:point});});},[socket,dispatch]);constemitFirstPointFromPlayer=(point:Point)=>{// (5)!socket.emit("FIRST_POINT_FROM_PLAYER",point);};constemitPointFromPlayer=(point:Point)=>{// (6)!socket.emit("POINT_FROM_PLAYER",point);};return(<WebSocketContext.Providervalue={{emitFirstPointFromPlayer,emitPointFromPlayer}}>{children}</WebSocketContext.Provider>);}functionuseWebSocket():State{constcontext=useContext(WebSocketContext);if(context===undefined){thrownewError("useWebSocket must be used within a WebSocketProvider");}returncontext;}export{WebSocketProvider,useWebSocket};
The state that the WebSocketProvider provides are two functions to send data to the backend.
A second useEffect function allows to keep the code clean. This useEffect is responsible to react to WebSocket events sent from the backend.
On the event FIRST_POINT_TO_PLAYERS, the point is dispatched to the LineProvider using its dispatch method.
On the event POINT_TO_PLAYERS, the point is dispatched to the LineProvider using its dispatch method.
Method to emit the start of a new line to the backend. The backend will then broadcast the message to the other players.
Method to emit the next point of a line to the backend. The backend will then broadcast the message to the other players.