Created
October 12, 2022 20:03
-
-
Save victusfate/668432425e87636bb9076654d655b1a3 to your computer and use it in GitHub Desktop.
great tip on using websockets with react, https://stackoverflow.com/questions/60152922/proper-way-of-using-react-hooks-websockets/60161181#60161181
This file contains hidden or 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 default function AppWs() { | |
const [isPaused, setPause] = useState(false); | |
const ws = useRef(null); | |
useEffect(() => { | |
ws.current = new WebSocket("wss://ws.kraken.com/"); | |
ws.current.onopen = () => console.log("ws opened"); | |
ws.current.onclose = () => console.log("ws closed"); | |
const wsCurrent = ws.current; | |
return () => { | |
wsCurrent.close(); | |
}; | |
}, []); | |
useEffect(() => { | |
if (!ws.current) return; | |
ws.current.onmessage = e => { | |
if (isPaused) return; | |
const message = JSON.parse(e.data); | |
console.log("e", message); | |
}; | |
}, [isPaused]); | |
return ( | |
<div> | |
<button onClick={() => setPause(!isPaused)}> | |
{isPaused ? "Resume" : "Pause"} | |
</button> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment