Coding task · JavaScript and React course · Module 10: React Ecosystem and Future

Practice: WebSocket Communication

WebSocket carries text, so you turn objects into JSON when sending (JSON.stringify) and back when receiving (JSON.parse(event.data)). Keep the socket in useRef so that send can reach it without another render, and close the connection in the useEffect cleanup, otherwise it stays open after the component unmounts.

Task

Finish the useMissionSocket hook that runs the comms channel to the station. The socket is created by createSocket(url) - in the preview it is a station simulator with the same interface as WebSocket. ___BLANK1___: in onmessage turn the text from event.data into a message object with JSON.parse. ___BLANK2___: the effect cleanup closes the socket with close() when the component goes away (also when StrictMode runs the effect twice). ___BLANK3___: send sends the object { text } turned into text with JSON.stringify. After a few seconds telemetry shows up in the preview, and every message you send comes back as an echo.