javascriptwebsocketdatatablesreal-time-updatesreal-time-data

Automatically Add rows to the Table when new data comes from a The Websocket with Javascript


I am new to JavaScript, not sure if this very basic question. I am trying to create a Bitcoin Price update dashboard using the data fetched from the external WebSocket. I managed to get the data from the WebSocket. The price updates every seconds, I am not sure how should I push the row data into a HTML table dynamically. I tried to iterate the array but still I am not able to proceed.

I have provided the code snippets below as well as external Websocket from where I am pulling the data.

Please let me know how should I insert the row dynamically into a HTML table. Thank you so much in advance.

<body>
    <table>
        <thead>
            <tr>
                <th scope="col">Price</th>
            </tr>
        </thead>
        <tbody  id="pricetable">
            
        </tbody>
    </table>

    <script>
        var binanceSocket = new WebSocket("wss://stream.binance.com:9443/ws/btcusdt@trade");
        binanceSocket.onmessage = function (event) {
        var messageObject = JSON.parse(event.data)
         console.log(messageObject.p);
    var table = document.getElementById('pricetable')
          }
    </script>
</body>

Solution

  • Assuming that you have your table in HTML ready with the row for Bitcoin as below. Then just select the <td> cell for price and format the figure accordingly before inserting to it's textContent.

    function insertRow(price){
      var tr      = document.createElement("tr"),
          tdCoin  = document.createElement("td"),
          tdPrice = document.createElement("td"),
          docFrag = new DocumentFragment();
      tdCoin.textContent = "BTC";
      tdPrice.textContent = `${Number(price.slice(0,-6)).toLocaleString("en-US",{style: 'currency', currency: 'USD'})}`;
      tr.appendChild(tdCoin);
      tr.appendChild(tdPrice);
      docFrag.appendChild(tr);
      return docFrag;
    }
    
    var binanceSocket = new WebSocket("wss://stream.binance.com:9443/ws/btcusdt@trade"),
        table = document.getElementById("pricetable");
    binanceSocket.onmessage = function(event) {
      var messageObject = JSON.parse(event.data);
      table.appendChild(insertRow(messageObject.p));
    }
    <body>
      <table>
        <thead>
          <tr>
            <th>Coin</th>
            <th scope="col">Price</th>
          </tr>
        </thead>
        <tbody id="pricetable">
        </tbody>
      </table>
    </body>