That's right. I will even go further and create a hook ( useWebsocket that uses useEffect internally) where you can pass the callback functions onopen and onmessage and returns a send function for instance or whatever you need from the hook.
Every time the client receives new message => setBids called => component rerender => create new instance of Websocket => create new connection (1 request in devtools). This's not good, right :)))
This is my idea. You can check more in network tab in devtools and see the differents.
constapiCall={event:'bts:subscribe',data:{channel:'order_book_btcusd'},};functionApp(){const[bids,setBids]=useState([0]);useEffect(()=>{constws=newWebSocket('wss://ws.bitstamp.net');ws.onopen=(event)=>{ws.send(JSON.stringify(apiCall));};ws.onmessage=function(event){constjson=JSON.parse(event.data);try{if((json.event=='data')){setBids(json.data.bids.slice(0,5));}}catch(err){console.log(err);}};//clean up functionreturn()=>ws.close();},[]);constfirstBids=bids.map((item,index)=>(<divkey={index}><p>{item}</p>
</div>
));return<div>{firstBids}</div>;
}
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
That's right. I will even go further and create a hook ( useWebsocket that uses useEffect internally) where you can pass the callback functions onopen and onmessage and returns a send function for instance or whatever you need from the hook.
Hey man, I wrote a reply to Vu's comment. Feel free to join the discussion :)
Every time the client receives new message =>
setBids
called => component rerender => create new instance of Websocket => create new connection (1 request in devtools). This's not good, right :)))This is my idea. You can check more in network tab in devtools and see the differents.