Add exclusively fresh entries to the Vue JS table

In my database table, new records are inserted every 10 seconds.

Using Vue and Axios, I am displaying the latest 20 records to the user in an HTML table.

In the created hook, I have implemented a method that fetches data every 5 seconds.

window.setInterval(() => {
            this.getRecentTrades()
          }, 5000)

Here is the code for my table rows:

<tr v-for="recenttrade in recenttrades" :key='recenttrade.id' v-bind:class="recenttrade.side=='Buy' ? 'text-success' : 'text-danger'">
    <td>{{ recenttrade.price }} </td>
    <td>{{ recenttrade.size }} </td>
    <td>{{ recenttrade.timestamp }} </td>
    <td>{{ recenttrade.side }} </td>
</tr>

How can I compare old records with the new ones and only add the new ones to the HTML table?

Answer №1

After reviewing the information found on https://v2.vuejs.org/v2/guide/list.html, it appears that replacing an array in Vue is best done by simply reassigning the local value with one from the API. Vue will automatically detect this change and only rerender the items that were not present in the previous update cycle.

Answer №2

If you're looking to compare two arrays and find the differences, you can create a function to help with that task.

function arrayDifference(arr1, arr2, identifier) {
    return [
        ...arr1.filter(item => !arr2.map(i => i[identifier]).includes(item[identifier])),
        ...arr2.filter(item => !arr1.map(i => i[identifier]).includes(item[identifier]))
    ];
}

To implement this in your `getRecentTrades` function, you can try something like the following:

getRecentTrades(){

    let self = this;
    apiCall.then(data => {
       let diff = arrayDifference(self.recenttrades, data, 'id');
       self.recenttrades.push(...diff);
    })

}

It's worth reconsidering your approach as fetching a large number of records over time may lead to performance issues with this method.

Answer №3

Instead of constantly updating the data each time you call getRecentTrades(), consider replacing it altogether. This way, only new items will be rendered and added to the list.

Update: As mentioned in the comment below, Vue has a binding mechanism called :key which prevents re-rendering of existing list items. With this feature, simply replacing the data when calling the function is more efficient as it only renders the new content.

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

Validating Inputs with an Array of Values in my Angular 2 Application

I have been exploring ways to retrieve data from an array of values instead of a single value when using [(ngModel)] binding in my Angular 2 application. The current setup functions perfectly with a single value, as shown below. The data is pulled from the ...

How to Generate an Array of JSON Objects in JavaScript on a Razor Page using a Custom ViewModel in MVC?

Attempting to populate the array within my script for future charting with D3.JS, I came across some issues. Following advice from this post, I used a specific syntax that unfortunately resulted in an error stating "Uncaught ReferenceError: WebSite is not ...

Is it possible to transfer values to Vue.js from within a server-rendered template (e.g. merging a Vue.js application with a django template)?

Is it possible to transfer values from a server-rendered template to Vue.js (e.g. linking a Vue.js app with a django template)? Possible Uses Enhancing specific pages within a server-rendered environment: Incorporate a basic Vue application on a singl ...

Running two blocks of scripts (utilizing lab.js as a loading manager)

I am currently facing an issue where I am trying to load two separate blocks of `lab.js` in different locations. However, when I attempt to utilize functions from the second block that are called from files loaded in the first block, they are showing as un ...

Activate one button out of several in Vue by clicking on it

I am working on a functionality where I have three buttons. When one button is clicked, it should become active while the other two become inactive. However, in my current code, all three buttons are changing together on the click event. Is there a more ...

Hydration has finished, but there are some discrepancies - Utilizing Ascii art within a vue component

I encountered an issue with displaying ascii art in the {{ name }} section of my component. While developing, a Vue warning popped up: Hydration text content mismatch in <pre> Followed by an error message: Hydration completed but contains mismatch ...

The selected value from the array in the scope model is not appearing correctly in the UI dropdown menu

I apologize for any linguistic errors in my communication. I have encountered an issue with the UI-Select select box while attempting to display data. Despite using a basic array, the ng-model value is returning as undefined. ...

Tips for sending multiple identical POST parameters

Currently, I'm in the process of developing a new user interface for a website that I frequently use. My approach involves utilizing Node.js along with request and cheerio to scrape data from various web pages. However, I've encountered an issue ...

Display the element following a specific component while looping through an array in Vue.js

Currently, I am facing an issue while using a for-loop on the component element. My goal is to display a <p> element next to the <component> element during the loop's third iteration. The challenge lies in accessing the iteration variable ...

What is required to create a basic application that can function offline while featuring an HTML/CSS user interface?

Newbie inquiry: I am interested in creating a small application that can run offline on a desktop computer. The amount of data to be saved is minimal, so I have the option to use a file or some type of database. However, my main question is: What languag ...

Approach for fetching these JSON records

I am currently exploring ways to retrieve all entries within a JSON payload using JavaScript. Specifically, I am interested in finding the best method to extract all instances of "o4" in a specific order (-159, -257). How can this be achieved? { ...

Having trouble compiling your Vue project and running into the "No mixed spaces and tabs" error?

Below are the details with an error: Error Details: Failed to compile. ./src/components/Header.vue Module Error (from ./node_modules/eslint-loader/index.js): H:\project\VueProjects\stock-trader\src\components\Header.vue 27: ...

Ways to ensure that v-model does not become "true" or "false" in an input checkbox using Vue

I am currently working on a filter popup that includes a list of checkboxes. By default, some items should be selected and others not selected. I have connected these checkboxes to an object array using v-model. My issue is that when I deselect and select ...

Encountering issues with the routing in my live Node.js project: ERROR

I am encountering issues with my project in production. I suspect it could be due to a misconfiguration or something similar. Could you please review the provided code snippets and see if you notice any potential issues? The project works fine locally, bu ...

Guide on fixing electron bug in vuejs vuetify project

I'm facing an issue with incorporating Electron into my Vue.js/Vuetify application. I'm uncertain about how to resolve the error mentioned below. These are the versions of the tools I am currently using: vue --version = @vue/cli 5.0.4 node -v ...

Creating a dynamic two-player chess application using Django - requiring the player's chess board to automatically update whenever the opponent makes a move

I am looking for a solution where each player has their own webpage equipped with a Javascript chessboard GUI interface that allows them to click and drag pieces. The challenge is ensuring that when one player makes a move, the other player's chessboa ...

Dial the Google App Scripts hotline

After successfully testing the query string in the browser for my published app script, I attempted to send an XMLHttpRequest to the script. However, upon doing so, I encountered the following error message: XMLHttpRequest cannot load https://script.goo ...

When the text for the Rails confirmation popup is sourced from a controller variable, it may not display properly

Attempting to customize my submit_tag confirmation popup within my Rails view, I encounter an issue when trying to utilize an instance variable from the Rails controller. Within the controller, I set up the variable as follows: @confirmation_msg = "test" ...

Ways to include external JavaScript in an HTML document along with CSS styling

Check out this code snippet in HTML with embedded JavaScript. I'm trying to externalize the JS file, but it's not functioning as expected when I do so. How can I resolve this issue and ensure that the element moves upon clicking when the script i ...

What is the reason for the find() method not displaying the most recent data from a MongoDB database in an Express.js application?

Upon calling the app.post('/form-submit', funtion(req, res)) method, my expectation is for it to first save the data using save(). This works fine, but then when I call the find() method, it shows all the data from the mongoDB database except for ...