Skip to content

Instantly share code, notes, and snippets.

@Zwiterrion
Created March 7, 2024 20:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zwiterrion/48c0328c240e58fcaa94aa01c4696bdf to your computer and use it in GitHub Desktop.
Save Zwiterrion/48c0328c240e58fcaa94aa01c4696bdf to your computer and use it in GitHub Desktop.
const ws = useRef();
const [connected, setConnected] = useState(false);
useEffect(() => {
// Create WebSocket connection.
const socket = new WebSocket(`ws://localhost:4444/bob`);
// Connection opened
socket.addEventListener("open", (event) => setConnected(true));
socket.addEventListener("close", (event) => setConnected(false));
// Listen for messages
socket.addEventListener("message", event => setMessages(messages => [...messages, JSON.parse(event.data.toString())]));
// store the WebSocket instance to send messages at a later time.
ws.current = socket;
}, []);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment