Add every WebSocket message to a div element in VUE3

Currently, I am facing an issue while attempting to display each trade from Binances Websocket Stream in my VUE3 component. The challenge I'm encountering is that only one line gets rendered and it keeps updating continuously. This is not the desired outcome that I intend to achieve. I appreciate any suggestions or solutions provided.

<template>
    <div>
        <div v-for="data in tradeDataList" :key="data.id">
            <div>
                {{ data }}
            </div>
        </div>
    </div>
</template>

<script>
export default {
  name: 'App',
  data: () => {
    return {
      connection: null,
      tradeDataList: [],

    }
  },

  created() {
        this.getTradeStream();
    },

  methods: {
      getTradeStream() {
        
        console.log("Starting connection to WebSocket Server");
        this.connection = new WebSocket("wss://stream.binance.com:9443/ws/btcusdt@trade");

        this.connection.addEventListener("message", (event) => {

            let tradeDataString = event.data;
            this.tradeDataList = [];

            let parsedData = JSON.parse(tradeDataString);
            this.tradeDataList = parsedData;

            console.log(this.tradeDataList);
        });

        this.connection.onopen = function (event) {
            console.log(event);
            console.log("Successfully connected to the echo websocket server...");
        };

      }
  }
}
</script>

I have already attempted using a v-for loop on this.tradeDataList with the expectation of getting a list where each trade appears on a separate line. However, instead of individual lines for each trade, I observed a single line that kept updating persistently without creating new lines.

Answer №1

Instead of clearing out this.tradeDataList = []; and replacing the item this.tradeDataList = parsedData;, consider using the push method to add the new item to the array. You can also remove old items using methods like splice.

new Vue({
  el: '#app',
  data: () => {
    return {
      connection: null,
      tradeDataList: [],

    }
  },

  created() {
    this.getTradeStream();
  },

  methods: {
    getTradeStream() {

      console.log("Starting connection to WebSocket Server");
      this.connection = new WebSocket("wss://stream.binance.com:9443/ws/btcusdt@trade");

      this.connection.addEventListener("message", (event) => {

        let tradeDataString = event.data;

        let parsedData = JSON.parse(tradeDataString);
        
        // push new item to array
        this.tradeDataList.push(parsedData);
        
        // keep only last 10
        this.tradeDataList = this.tradeDataList.slice(Math.max(this.tradeDataList.length - 10, 0))
      });

      this.connection.onopen = function(event) {
        //console.log(event);
        console.log("Successfully connected to the echo websocket server...");
      };

    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.14/vue.min.js"></script>

<div id="app">
  <div>
    <div v-for="data in tradeDataList" :key="data.id">
      <div>
        {{ data.t }} - {{ data.p }}
      </div>
    </div>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React does not recognize the event.which property as undefined

I'm currently working on limiting the input in a text field to only numbers, backspace, or space. I've tried checking before I set the state and preventing the default behavior of the event in other cases, but I can't seem to find the event. ...

Error during deployment on Vercel: Module 'build-rss.js' not found in workpath0 directory

One of my package.json scripts looks like this: { "export": "next export", "build": "next build && npm run export && npm run build:rss", "build:rss": "node ./.next/server/scripts/bui ...

Issue with displaying Jquery AJAX response in specific div

Having trouble with my JQUERY function. I've got an onclick event triggering a dialog box to open. But upon opening, the dialog box calls two separate jQuery functions. Both functions are supposed to fetch member information based on ID, but only on ...

LiveValidation plugin causing issue with removing dynamically inserted elements

My form validation is powered by the Live Validation plugin. After submission, the plugin automatically inserts a line of code like this one: <span class=" LV_validation_message LV_valid">Ok</span> However, I encountered an issue when trying ...

What is the best way to incorporate products as components into the cart component?

ProductCard import React from 'react'; import { Card, Container, Row, Col, Button} from 'react-bootstrap'; import Cart from './Cart'; import './ItemCard.css'; function ProductCard(props){ return( <Car ...

When a label is clicked, the ng-change event is not triggered on the corresponding radio button

I developed a custom directive that allows you to select a radio button by focusing on its label and pressing the spacebar. However, although the radio button is checked, the ng-change function action() does not get triggered. Below is the HTML code snipp ...

Discover the power of integrating JSON and HTTP Request in the Play Framework

My aim is to develop a methodology that can effectively manage JSON and HTTP requests. This approach will facilitate the transition to creating both a Webapp and a Mobile App in the future, as JSON handling is crucial for processing requests across differe ...

Ways to eliminate the vertical scroll feature in a kendo chart

I am encountering an issue while loading a kendo chart inside grid-stack.js where I am unable to resize the height properly. Whenever I decrease the height, a vertical scroll appears which should not happen. I have tried setting the height to auto and refr ...

Include the server $HOSTNAME in the JavaScript file of the client

Currently, I have a JavaScript code running on the client-side which contains a websocket address for server communication: new WebSocket("ws://localhost:3000/") Everything is operating fine, but my goal is to replace 'localhost' with the $HOST ...

Expand the data retrieved from the database in node.js to include additional fields, not just the id

When creating a login using the code provided, only the user's ID is returned. The challenge now is how to retrieve another field from the database. I specifically require the "header" field from the database. Within the onSubmit function of the for ...

Ionic 2's Navigation Feature Failing to Function

I need to implement a "forgot password" feature on my login page. When a user clicks the button, they should be redirected to the "forgot password" page. Below is the code snippet from my login.html <button ion-button block color="blue" (cli ...

What are some ways to display multiple divs within a single popup window?

I am attempting to create the following layout: https://i.sstatic.net/OzE98.png Here is what I have been able to achieve: https://i.sstatic.net/7GxdP.png In the second picture, the divs are shown separately. My goal is to display the incoming data in a ...

How can you transfer data from a Writable Buffer to a ReadStream efficiently?

How do I convert a writable stream into a readable stream using a buffer? This is my code to store data from an ftp server in an array of chunks: let chunks = [] let writable = new Writable writable._write = (chunk, encoding, callback) => { chunks.p ...

Substitute the nested object's value with a variable structure

I have an object structured like this: const obj = {a: {x: 0, y: 0}} but it can also be structured like this: const obj = {a: {x: 0, y: 0}, b: {x: 10, y: 3}, abcd: {x: -1, y: 0}} This means that the obj can contain multiple keys with variable key names. ...

Getting a 401 error when using the Companies House API with jQuery and ajax

I attempted to retrieve JSON data from the UK Companies House API but encountered a 401 error An error occurred: the server responded with a status of 401 (Unauthorized) I implemented jQuery with the ajax() method for this task, and here is a snippet o ...

Steps for dynamically loading the correct pane without having to refresh the header, footer, or left navigation

Looking to create a web application using HTML, Bootstrap, and jQuery that includes a header, footer, left navigation, and right pane. The content of the right pane will be loaded from a separate HTML page based on what is clicked in the left navigation. ...

Making If Statements Easier

Currently, I'm tackling an assignment that involves utilizing if statements and switch statements. Here is a snippet of code that I am working on: if (validateField(document.forms[0].name) == false) { isValid = false; } if (validateField(docume ...

Confusing postback phenomena in ASP.NET web forms

I have developed a small script that successfully maintains the focused element during an async postback. However, I encountered an issue when tabbing through controls generated inside an asp:Repeater, where a full postback is unexpectedly triggered. Below ...

Manually adjust rotation in Three.js by clicking

I am looking to initiate an animated rotation of an object by clicking a button. I have a basic understanding that the render function operates as an infinite loop and that adding 0.1 to cylinder.rotation.x continuously rotates the object. My goal is to ...

I ran into an issue trying to modify the color and thickness of the divider line in MaterialUI

Check out my code on codesandbox here. I'm trying to adjust the line thickness and color of the separator in my MaterialUI project, but I'm having trouble getting it to work. I've looked at a few examples, but nothing seems to be working for ...