What is the most effective method for appending elements to an array using a Svelte store subscription?

I want to store objects in an array in a component every time a subscribed store is updated with data from a WebSocket. My goal is to display the last N data points I have received (N=1000 for instance).

The store is defined in socket.js:

import { readable } from 'svelte/store';

export const datastream = readable([], set => {
  let socket = new WebSocket("ws://localhost:8765")
  let data = [];

  socket.onmessage = function (event) {
    let { time, value } = JSON.parse(event.data);

    // update the data array
    // TODO: set a max buffer size
    data = [...data, {"time": time, "value": value}];

    // set the new data as store value
    set(data)
  }
})

I have a Chart.svelte component where a) the last N points should be plotted (implementation not shown), and b) it should update every time the store subscription callback is triggered. The challenge is that I may need to preprocess the WebSocket data before using it. In Chart.svelte:

<script>
  ...
  import { datastream } from './socket.js';

  export let plot_data;

  const unsubscribe = datastream.subscribe(data => {
    plot_data = []
    for (let datum of data) {
      plot_data = [...plot_data, {x: datum.time, y: datum.value}]
    }
  });

  $: {...
      some stuff that sets up plotting
  ...}
</script>

<div class='my-chart'>
    ...(plot_data)
</div>

My concern is whether this is the most effective approach. It works, but I have a duplicate array in the datastream store, and I rebuild the plot_data array completely each time a new value is received.

I tried subscribing to only the most recent data point in the store, but I couldn't find a way to capture the store update and trigger a new entry into the plot_data array to refresh the plot.

Answer №1

Are you interested in this information:

Check out this code example: updating data in batches

However, utilize this repository for your needs:

let connection = new WebSocket("ws://localhost:8765")

const dataFeed = readable(null, set => {
  connection.onmessage = function (event) {
    set ({ time, value } = JSON.parse(event.data));
  };
});

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

working with html data in a bootstrap modal using javascript

Utilizing an id, I pass data to a bootstrap modal and link that id with stored data. $("#fruit").html($(this).data("fruit")); In addition, I am appending data to the bootstrap modal $('#mymodal').find('.modal-body').append('< ...

Supporting server-side routing with NodeJS and Express for AngularJS applications

My current setup includes NodeJS + expressJS on the server and AngularJS on the client side. The routes defined in my AngularJS controller are as follows: app.config(function($routeProvider,$locationProvider) { $routeProvider .when('/field1/:id&apo ...

How come the rotation of my Three.js mesh gets thrown off when I adjust the scale?

I managed to achieve my goal of rotating a sphere around the x and y axes using the following code: // Update ball rotation. var tempMat = new THREE.Matrix4(); tempMat.makeRotationAxis(new THREE.Vector3(0,1,0), stepX/ballRadius); tempMat.multiplySelf(ball ...

Load a script in a specific div using React

Can anyone assist me with loading a script onto a specific component in my React application? Here is the script that needs to be loaded at the bottom-most div within my component: <div id="rexxxx"></div> <script> new carouselI ...

Can a placeholder dropzone be created at the bottom of Vue Draggable lists?

Currently, I am utilizing Vue.Draggable (accessible at https://github.com/SortableJS/Vue.Draggable) to develop a kanban board that enables me to drag items from one list to another. A challenge I face is that when dragging a list item to the bottom of anot ...

What is the best way to arrange an associative array based on a specific field?

I'm facing an issue with sorting the $lessons array based on the 'available' field. This array includes the lesson ID and the start time in epoch format. My goal is to organize the lessons starting from the one due soonest. Despite searching ...

What is a way to simulate division using only multiplication and whole numbers?

The issue at hand: The stack-building API that I'm currently using in rapidweaver has limitations when it comes to division or floats, making it challenging to perform certain mathematical operations. Insights into the API's rules: This partic ...

Input specific ng-if conditions

I'm a bit confused about the conditions for my ng-if and could use some assistance. I have a form on my page that is rendered using ng-repeat and a couple of custom filters. You can check out this plunker. The issue I'm facing is that I need to p ...

Unable to invoke Kendo JavaScript

I'm facing an issue with my source code where I am trying to call kendo.all.min.js. Everything works fine when I call kendo.common.min.css and kendo.default.min.css, but as soon as I try to call kendo.all.min.js, I encounter the following error: http ...

React-NextJS encountered an error: TypeError, it cannot read the property 'taste' because it is undefined

Recently, I've been encountering an issue with NextJS that keeps throwing the error message: TypeError: Cannot read property 'taste' of undefined. It's quite frustrating as sometimes it displays the expected output but most of the time ...

The Google Javascript API Photo getURL function provides a temporary URL that may not always lead to the correct photo_reference

Currently, I am integrating Google Autocomplete with Maps Javascript API into my Angular 5 application. As part of my website functionality, I fetch details about a place, including available photos. The photo URL is obtained through the getURL() method. ...

Replacing child routes with an Angular wildcard route

I'm facing an issue with integrating a module named "host" into the app-routing.module. The problem I encountered is that the wildcard route takes precedence over loading the Host component, leading to the display of the PageNotFoundComponent instead. ...

Is it possible to convert milliseconds into the format HH:MM:SS:UU using either JavaScript or PHP?

Is there a way to convert integer milliseconds, for example 619308, into a format like HH:MM:SS:UU using JavaScript or PHP? My apologies for any language errors. ...

Creating an HTML table with jQuery

I've almost got it working, but something's missing. I'm creating an HTML table using JQuery with a list of names populating the first column. The structure is fine overall, including the header and colgroups. However, I'm having troubl ...

Ways to prevent npm script from running automatically in the background

When working with npm scripts, I have a situation where some tasks need to run in parallel. My setup looks something like this: ... scripts: { "a": "taskA &", "preb": "npm run a", "b": "taskB" } ... Everything works well so far! But I am won ...

Issue with Jquery Slider Showing Empty Slide

Currently addressing issues with the slider on my site, which utilizes SlidesJS at . There seems to be a problem where it shows a blank slide inexplicably. After investigating, I noticed that a list element is being added to the pagination class, but I can ...

Issue: app.database function is not recognized with Firebase

I'm attempting to integrate Firebase realtime database into my Vue application, but I keep encountering the following error: TypeError: app.database is not a function This is what my code looks like: File: Firebase.js var firebase = require(' ...

Content not being displayed by Javascript

I'm having trouble displaying content using JavaScript DOM. Every time I try to run my code, the page comes up blank. Here is an example of my HTML file: <!DOCTYPE html> <html> <head> <title>Radiant HQ</titl ...

Understanding the scope of variables in HTML files, JavaScript files, and PHP files when echoing statements

Is there a way to define a global javascript variable that can be accessed from multiple places within an HTML page? I need the variable to be accessible in three specific locations: Within the code of the HTML page favorites.php. Inside a separate javas ...

Identifying added elements that respond to link hover effects

I've been working on a project where I'm trying to replace the default browser cursor with an SVG one using jQuery. Everything seems to be working smoothly, except for changing the cursor when it hovers over links - nothing I've tried so far ...