Created
October 17, 2022 14:47
-
-
Save cocodrino/7c4b486e41f5079bfb2725ebf8cccd3e to your computer and use it in GitHub Desktop.
wesocket react
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const WebsocketContext = createContext(false, null, () => {}); | |
// ready, value, send | |
// Make sure to put WebsocketProvider higher up in | |
// the component tree than any consumers. | |
export const WebsocketProvider = ({ children }) => { | |
const [isReady, setIsReady] = useState(false); | |
const [val, setVal] = useState(null); | |
const ws = useRef(null); | |
useEffect(() => { | |
const socket = new WebSocket("wss://echo.websocket.events/"); | |
socket.onopen = () => setIsReady(true); | |
socket.onclose = () => setIsReady(false); | |
socket.onmessage = (event) => setVal(event.data); | |
ws.current = socket; | |
return () => { | |
socket.close(); | |
}; | |
}, []); | |
const ret = [isReady, val, ws.current?.send.bind(ws.current)]; | |
return ( | |
<WebsocketContext.Provider value={ret}> | |
{children} | |
</WebsocketContext.Provider> | |
); | |
}; | |
And there’s our context! To use it, we just need to create a consumer. | |
// Very similar to the WsHook component above. | |
export const WsConsumer = () => { | |
const [ready, val, send] = useContext(WebsocketContext); // use it just like a hook | |
useEffect(() => { | |
if (ready) { | |
send("test message"); | |
} | |
}, [ready, send]); // make sure to include send in dependency array | |
return ( | |
<div> | |
Ready: {JSON.stringify(ready)}, Value: {val} | |
</div> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://web.archive.org/web/20231210211844/https://www.kianmusser.com/articles/react-where-put-websocket/