React.JS update a websocket value into an object

Viewed 1120

I am tring to dynamically create a stock price table with live stock price using websockets. I am getting all the nexessary data and want to update my object value for stock price with the live price. How do I access the variable and insert value into the object. The data variable gets the live stock price.

import './App.css';
    import * as ReactBootStrap from "react-bootstrap";
    import { w3cwebsocket as W3CWebSocket } from "websocket";
    import React, { useEffect, useState } from 'react';



    function App() {
      
      const stockPrice = document.getElementById('stockPrice');  
      const [stocks, setStocks] = useState([0])
      const client = new W3CWebSocket('ws://localhost:9080/user');
    
      
      useEffect(() => {
        client.onopen = () => {
          console.log('connected to localhost:9080');
        }
        client.onmessage = (e) => {
          let page = JSON.parse(e.data);
          let x = page.Update;
          let data = x.Data[0].RowData[4];
          console.log(data);    
          function getData() {
            setStocks(currStock => currStock+data) ; 
          }            
        }
        return () => {         
        }
      }, [])
     
    
      const stocks1 = [
        {serialnumber:"1", accountnumber:"Account1", ticker: "AAPL", stockprice:""},
        {serialnumber:"2", accountnumber:"Account2", ticker: "GME", stockprice:""} ,
        {serialnumber:"3", accountnumber:"Account3", ticker: "IBM", stockprice:""} ,
        {serialnumber:"4", accountnumber:"Account4", ticker: "CS", stockprice:""} ,
        {serialnumber:"5", accountnumber:"Account5", ticker: "MSFT", stockprice:""} ,
        {serialnumber:"6", accountnumber:"Account6", ticker: "INTC", stockprice:""}   ]
       
      
        const renderStocks = (stock, index) => {
          return(
            <tr key={index}>
              <td>{stock.serialnumber}</td>
          <td>{stock.accountnumber}</td>
          <td>{stock.ticker}</td>
          <td id="stockPrice">{stock.stockprice}</td>
            </tr>
      
          )
         
        }    
     
    
      return (
        <div className="App">
          <ReactBootStrap.Table striped bordered hover>
        <thead>
          <tr>
            <th>Serial Number</th>
            <th>Account Number</th>
            <th>Ticker</th>
            <th>Stock Price</th>
          </tr>
        </thead>
        <tbody>
          {stocks1.map(renderStocks)}
        </tbody>
        </ReactBootStrap.Table>
        </div>
      );
    }
    
    export default App;
1 Answers

There are two things you should implement. The first one is to keep your actual data as state. For functional components you can do it using 'useState' hook. The second one is keeping fetching within 'useEffect' hook. Finally you should come to something like this:

const App = () => {
  const [stocks, setStocks] = useState([])
  useEffect(() => {
    // here you open websocket connection just like you do it now
    ...
    client.onmessage = () => {
      // here you get the updated details
      setStocks({objectWithNewStocksDetails}) // react, update state please
    }
    
    return () => {} // useEffect returns cleanup function - close connection here

  }, []) // an empty dependencies array says it fires once

  // after all you just return jsx
  // btw you can use conditional returns in case you do not have data to show yet:
  if (stocks.length === 0) return <div>Loading...</div>

  return (
    <div className="App">
      ...
    </div>
  )
}
Related