I am trying to use websockets to connect to Kraken websocket API. I create a new instance and setup listeners on intitial render. I am trying to make buttons to subscribe and close but the buttons are not working.
I am using this websocket library.
const WebSocket = require('isomorphic-ws')
function App() {
const ws = new WebSocket('wss://ws.kraken.com')
useEffect(() => {
ws.onopen = () => {
console.log('connected')
}
ws.onmessage = (msg) => {
const message = JSON.parse(msg.data)
const sub = message[2]
console.log(message)
}
ws.onclose = () => {
console.log('closing connection')
// ws.close()
}
return () => {
ws.close()
}
}, [])
const wsClose = () => {
ws.close()
}
const wsSub = () => {
ws.send(JSON.stringify(
{
"event": "subscribe",
"pair": [
"XBT/USD"
],
"subscription": {
"name": "ticker"
}
}
))
console.log('send subscribe')
}
return (
<button onClick={wsSub}>subscribe</button>
<button onClick={wsClose}>close ws</button>
)
}
export default App
If I put the code from the wsSub function under the ws.onopen listener the subscription works, but I want to have control over the subscriptions not subscribe when the websocket is opened. I am using buttons like this for testing. I want to subscribe and unsubscribe based on user form submission but I feel like I should be able to get this working first.