Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

89
Visualizações
Close and make new connection to websocket when state changes React

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]);

about 4 years ago · Santiago Gelvez
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda