Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

88
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda