I am using the finnhub websocket and it returns info based on which stocks you subscribe to. Whenever a stock is added to my list it will send a message to the websocket to subscribe as well as add the stock to my stock list array. I want to constantly check for messages so I want to keep the connection open the entire time. When the stock list is updated the state should change but it does not. I think it is because the socket is still open but I'm not entirely sure. If it is, I want to close the socket and update the state before reopening a connection anytime a stock is added so that the updated list can be used, but I am not sure how to go about this. I can't close the socket in the same useeffect because I need the constant flow of messages and putting it in its own useeffect close the socket before it is even connected.
const [stockList, setStockList] = useState([]);
const socket = useRef("");
const webSocketData = useRef("");
const filteredWS = useRef("");
const add = () => {
setStockList([...stockList,{ Tick: currentStock.symbol, Name: currentStock.name },]);
socket.current.send(JSON.stringify({ type: "subscribe", symbol: currentStock.symbol }))
};
useEffect(() => {
// Websocket Connection
if (!socket.current) {
socket.current = new WebSocket(`wss://ws.finnhub.io?token=${apiKey}`);
}
socket.current.onopen = () => {
console.log("websocket open");
socket.current.onmessage = (e) => {
webSocketData.current = JSON.parse(e.data);
try {
let wsData = webSocketData.current.data.map((val) => {
return { lastPrice: val.p, Tick: val.s };
});
let copyStockList = [...stockList];
filteredWS.current = copyStockList.map((val1)=>{
return wsData.find((val2) => {
if (val2.Tick === val1.Tick) {
return {Tick:val2.Tick, lastPrice:val2.lastPrice};
}
}
);
})
} catch {
console.log("Websocket not working");
}
};
socket.current.onclose = () => {
console.log("web close");
};
}, [stockList]);