Attempting to automatically invoke the API every minute, rather than relying on the user to reload the page

I currently have fetchCoins() in my mounted() function, which calls the API whenever a user refreshes.

My goal is to call the API once, store the data in local storage, and then retrieve the data every minute.

methods: {
    async fetchCoins() {
      const response = await fetch("https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=false&price_change_percentage=1h");
      const data = await response.json();
      this.coins = this.coins.concat(data);
    },

    setData() {
      localStorage.setItem('coin-info', JSON.stringify(this.coins))
    },

    getData() {
      let get = localStorage.getItem('coin-info', []);
      this.coins = JSON.parse(get);
      console.log(this.coins);

      setInterval(() => {
        this.fetchCoins()
      }, 60000);
    },
}

Answer №1

In order to track the date of the last fetch in localStorage, you can use the following implementation as a guide:

   setNextFetchCoins() {
       const lastFetch = new Date(localStorage.getItem('coin-info-last-fetch'));
       
       const timeElapsed = Date.now() - lastFetch.valueOf();
       const nextCall = Math.max(60000 - timeElapsed, 0);
       
       setTimeout(() => {
           this.fetchCoins();
           localStorage.setItem('coin-info-last-fetch', new Date());

           this.setNextFetchCoins();
       }, nextCall)
   }

Remember to update the this.fetchCoins() call in the mounted function with this method.

Note that there are some considerations to keep in mind regarding this code snippet:

  • The accuracy of setTimeout and setInterval functions may vary slightly due to delays in execution. If precision is crucial, explore alternative solutions like the one mentioned in this thread.
  • This code is tailored for a single instance of the component. Using it for multiple components could lead to conflicts when writing to coin-info-last-fetch.
  • The fetching loop continues indefinitely, even after the component is destroyed. To address this, store the timeout id returned by setTimeout in the component's data for eventual clearing.

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

CSS modified after opening a modal dialog that has loaded external HTML content

Within my ASP.NET MVC project, I am utilizing a tab wizard. On one of the tabs, I trigger a modal dialog by loading HTML content from an external API. However, once I close the wizard and navigate to the next tab, the table style (specifically border color ...

Interactive real-time search results with clickable option through AJAX technology

Currently, I have implemented a live search feature that displays results based on what the user types in real time using the keyup function. However, one issue I encountered is that the displayed results inside the <div> tag are not clickable. Is th ...

Use a personalized CSS class with the Kendo Dropdown Widget

Is there a way to assign a custom CSS class to the dropdown HTML container that is created when using the .kendoDropDownList() method on a <select> or <input> element? In this fiddle ( http://jsfiddle.net/lav911/n9V4N/ ) you can see the releva ...

Automatically assigning a FormData key/value pair upon clicking using Puppeteer in NodeJS

While working on a NodeJS project, I am using Puppeteer to fill out a form. So far, the regular type and click functions work perfectly. After clicking the "submit" button, a POST request is sent to the server with some form data. I want to add a key/value ...

What is the procedure to change a matter body's isStatic property to false in matter.js upon pressing a key?

During my recent project, I encountered a challenge in trying to set the isStatic property of a Matter Body in matter.js to false when a key is pressed. if (keyIsPressed(UP_ARROW)) { this.body.isStatic(false) } Could you provide guidance on the correct ...

Trouble with Vuetify autocomplete not showing loading indicator

My issue revolves around an autocomplete field that loads data from the backend. Below is a simplified version of the code: <div class="form-row"> <v-autocomplete :solo="true" v-model="user.place.value" :ite ...

How can I import a JavaScript file from the assets folder in Nuxt.js?

I have explored multiple methods for importing the JS file, but I am still unable to locate it. Can anyone guide me on how to import a JS file from the assets folder to nuxt.config.js and have it accessible throughout the entire website? nuxt.config.js he ...

Access to a custom Google Map via an API connection

I currently have multiple custom Google Maps that I created using and they are all associated with my Google account. Is it possible to access these maps using the Google Maps JavaScript API? It seems like the API does not work with manually created maps ...

Error message: Unable to access $controller with AngularJS and Karma

As someone who is just starting with testing, I figured it was a good idea to begin testing this project. However, when I execute grunt karma:watch, I encounter an error related to the configuration files. My config file includes: module.exports = functi ...

Reducing the slide margins in impress.js?

When using Impress.js, I noticed that the default slides have a large left margin (or padding - it's hard to determine with Firefox's Inspector). I have a slide with a wide <pre> block that would fit if it were aligned to the left, but it d ...

What is the best way to develop a widget that loads asynchronously by implementing AJAX, JavaScript, and PHP?

Currently, this widget is in need of items that are sourced from a php file. For instance, the javascript function should generate a table within this div element. <div id="widget"></> The aim is to dynamically update the content with the ht ...

Using jQuery to iterate through elements of a PHP array

I've got a PHP array that outputs like this: Array ( [0] => Array ( [title] => Much title [end] => Such end [start] => Very start ) [1] => Array ( [title] ...

What is the best way to keep the navbar contained within the parent div (hero image) no matter the size of the screen?

After working on adjusting my website layout for different screen sizes, I encountered an issue with the navbar overflowing the parent image when viewed on my laptop. Despite trying both relative and absolute positioning for the .navbar element and setting ...

Tips on implementing multiselect functionality in sails.js with the use of built-in Vue and AJAX forms

Has anyone successfully implemented a simple multiselect form in Sails.js 1.0 using ajax and Vue? I followed the instructions on the Vue.js website, but I keep encountering errors: The error messages displayed on screen are as follows: Error: In directive ...

What is the method for inserting an icon using createElement?

Can someone help me figure out how to create a Material-UI icon using JavaScript? I am currently using the Material-UI-icon library. import ThumbUpIcon from '@material-ui/icons/ThumbUp'; var thumbsup = document.createElement(ThumbUpIcon); Any ...

Find out whether the object is located behind another item

Is there a method to determine if elementA is "obscured" by another element, meaning it is not visible to the user? We could potentially achieve this using stacking context, but the challenge lies in identifying which elements to compare. This would requi ...

Acquire feedback from PHP using SweetAlert notifications

I need to update my HTML form to function like this: <script> function getName() { var name = $('#name').val(); var url_send = 'send.php'; $.ajax({ url: url_send, data: 'name=' + name, ...

Deciphering the intricacies of the http request

I encountered an issue while trying to send a POST request using jQuery AJAX. Upon making the request, I received the following error: XMLHttpRequest cannot load. Response for preflight has invalid HTTP status code 403 Now, I am unsure if the mistake i ...

Struggling to construct a project using parcel, continually encountering issues with unsupported file types

My attempt at creating a project using parcel has hit a snag. Despite diligently following the guidelines provided in my assignment, an error message consistently appears in my terminal each time I initiate the command: parcel src/index.html The error mes ...

The universal vue entity is not defined

Initially, I wanted to reuse my validator in another component, so I placed it in the myValidator.js file. I made sure to set the Vue object to window since I needed internationalization (i18n) in my myValidator.js. However, I encountered an error message ...