Execute a VueJS API call every 20 minutes

I am retrieving data from an API endpoint to display information about coin names. I would like this information to update every 20 minutes, but for testing purposes, I have set it to refresh every 500 milliseconds. However, my current approach of fetching data continuously and appending it to the existing list is causing a problem with duplicate keys, specifically 'BUSDRON'. This has resulted in errors and freezing issues in my app.

How can I modify my fetch logic to only retrieve new data from the API link every 20 minutes without duplicating values? Below are the methods I am currently using:

 methods: {
    async fetchApi() {
      const response = await fetch(
        'https://api2.binance.com/api/v3/ticker/24hr'
      );
      const data = await response.json();
      await data.forEach(element => {
        this.chartData.symbols = [...this.chartData.symbols, element.symbol];
        this.chartData.price = [...this.chartData.price, +element.lastPrice];
      });
    },
}



 data: () => ({
        timer: '',
    )}


async created() {
    this.loaded = false;

    try {
      this.timer = setInterval(this.fetchApi, 500);

      this.loaded = true;
    } catch (e) {
      console.error(e);
    }
  },

Answer №1

Utilize the uniqBy function from lodash to eliminate duplicates.

If uncertain about the uniqueness being based on the most recent data, it is advisable to reverse the array for safety measures. Once the unique data has been filtered, reverse the array again to maintain the correct order.

methods: {
    async fetchApi() {
      const response = await fetch(
        'https://api2.binance.com/api/v3/ticker/24hr'
      );
      const data = await response.json();
      this.chartData = _.uniqBy([...this.data, data].reverse(), 'symbols').reverse()
    }
}

Answer №2

In preparation for the forEach loop, it is recommended to clear out the existing arrays for symbols and price by resetting them to empty arrays. Then, within the loop, populate these arrays with the new values.

const response = await fetch(
    'https://api2.binance.com/api/v3/ticker/24hr'
  );
const data = await response.json();
const symbols = [];
const price = [];

data.forEach(element => {
  symbols.push(element.symbol);
  price.push(element.lastPrice);
});

this.chartData.symbols = symbols;
this.chartData.price = price;

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

Modifying an item within an array of Mongoose models

I am working with a model schema that looks like this: { _id: foo cart: { items: [ { id: number name: string, } ] } } My goal is to locate the document by its id and then modify the name value of the object in ...

Assign the input text field's value programmatically in the code-behind of a C# Asp.net application

I am attempting to change the value of an HTML input field from C# code behind. These inputs are created through a JavaScript loop, so I have not had much success using run at server or assigning values through <%= %>. Below is my script: var mytab ...

Non-responsive behavior triggered by a button click event (JavaScript)

Help needed with displaying results on the same page for an online calculator I'm creating. Why are the results not showing up as expected? I want users to input 4 pieces of information, have the logic executed, and then display the answers below th ...

Tips for capturing the Three.js model file content and assigning it to a variable

After exporting a model from Blender to Three.js, the resulting file contains JSON data. There are two methods I know of for loading this model: var loader = new THREE.JSONLoader() var material = new THREE.MeshPhongMaterial({color: '#8080a0'}) ...

React Native application fails to return any values from an asynchronous operation in App function

Completely new to React Native, this is my first attempt at coding. I'm struggling with returning jsx from my App() function due to an asynchronous operation within it. Here's the code that I believe clearly demonstrates my issue: import React fr ...

Tips for inserting HTML-tagged data into a database using AJAX and PHP

var id=$("#id").val(); var status=$("#status").val(); var jtitle=$("#jtitle").val(); function submitData(){ var id=$("#id").val(); var status=$("#status").val(); var jtitle=$("#jtitle").val(); var jdesc=tinyMCE.acti ...

Add a new variable to the data in a jQuery ajax request for each request with any updates

I've encountered an issue with the code below, which is meant to add additional data to any ajax request made by my app. It works fine when the page first loads, but because my application is single-page and ajax-based, I need the updated variable val ...

Mongoose schema nesting guide

I've encountered an issue while attempting to nest schemas in mongoose, and unfortunately I'm struggling to pinpoint the exact cause. Here's what my current setup looks like. Starting with the parent schema: const Comment = require("./Comm ...

Sluggish performance in the DOM due to high input lag (with over 80 or more components within a single template, each with its own watcher)

Whenever I try to input, check a box, or select a radio button, the DOM lags and responds slowly. This issue seems to be present in every component with similar code. <template> <div> ...some temporary example... <input v ...

Creating code that is easily testable for a unique test scenario

My function, readFile(path, callback), is asynchronous. The first time it reads a file, it retrieves the content from the file system and saves it in memory. For subsequent reads of the same file, the function simply returns the cached content from memor ...

Troubleshooting the issue of "Mismatched transaction number*" in MongoDB and Node.js

While trying to add data, I encountered an issue with modifying two schemas using ACID transactions in MongoDB with Node.js. Upon running the program, an error was displayed: (node:171072) UnhandledPromiseRejectionWarning: MongoError: Given transaction n ...

incorrect calculation of date difference using momentjs

Currently utilizing countdown.js for a project where I need to add 60 days to a date fetched from the database. Successfully implemented this in the targetDay variable and it's functioning properly. However, when attempting to calculate this date fro ...

Having trouble selecting a radio button in React JS because it's marked as read-only due to the check attribute

In my scenario, I have a child component with radio buttons. The questions and radio buttons are populated based on the data, with each set consisting of one "yes" and one "no" option. I am attempting to automatically check all radio buttons that have a v ...

Utilizing clip-path polygons for effective styling on Firefox and iOS

I have been working on a plugin to create animated modal boxes by utilizing the clip-path property. However, I have encountered an issue where this code only seems to work in Chrome. You can view the codepen demo here. Unfortunately, it appears that Firef ...

"Double the Data: A D3.js JSON Tale of Two Creators

I found inspiration from this example: http://bl.ocks.org/mbostock/1062288 to create a collapsible Force Layout. One challenge I'm facing is how to display a graph where a single node is connected to two parent nodes. father father | | ...

Refresh a single Object Key in React.js

Hey there, I'm currently working on updating book information via a PUT request to my API. My goal is to send only one property at a time, while keeping the rest unchanged. The issue I'm facing is that if I send just one property, the others are ...

Experiencing Challenges with JavaScript Implementation Within an HTML Document

Code: <!DOCTYPE html> <head> <script type="text/javascript" src="jquery-3.3.1.js"> </script> <script type="text/javascript"> $(function() { alert("Hello World"); }); </script> <meta charset ...

Arrange fixed-position elements so that they adhere to the boundaries of their adjacent siblings

Is there a way to keep two fixed elements aligned with their sibling element on window resize? <div class="left-img"> IMAGE HERE </div> <!-- fixed positioned --> <div class="container"> Lorem ipsum... </div> <div class=" ...

The function .css() in jQuery is malfunctioning

This task should be a piece of cake... All I want is to hide the buttons when a user is logged in and display the log out button instead. jQuery().ready(function($) { if ($("body").hasClass("logged-in")) { $(".logged-out-button").css("display", " ...

Counting the number of times a form is submitted using a submit button and storing the data

After researching for a few hours, I've gathered information on different techniques for storing data related to a submit button counter in a text file. <form action="/enquiry.php" method="post" name="form"> <label>Name *</label> &l ...