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

What is the best way to set up and customize multiple Vue Instances using Laravel Mix?

Currently, I am working on a PHP project that involves using Laravel and Vue.js. My main goal is to manage the Admin and Client functionalities separately by adding an additional Vue Instance. However, I am struggling with creating and setting up this in ...

Ways to display a default view in React

I am working on a React website that has three different routes. My goal is to have the first route, named Home, automatically displayed when a user lands on the site. Below is the code snippet from my App.js: <Router> <Navigation /> <Sw ...

I keep encountering an error stating that parameter 1 for 'FormData' is not of type 'HTMLFormElement'. I am struggling to resolve this issue on my own. Can someone please assist me with fixing this problem?

Here is the snippet of code that I am struggling with: const authForm = useRef(); const handleSubmit = (e) => { e.preventDefault(); //formData let form = new FormData(authForm.current); console.log(form) } This code snippet shows how I added a ...

The attribute "value" for Material-UI autocomplete cannot be used in conjunction with the "getOptionLabel" attribute

<Autocomplete id="license-select" options={licReqList} value = {licReqList[0] ? licReqList[0].licReqStr : null} getOptionLabel={(option) => option.licReqStr} onChange={ha ...

What is the best way to retrieve ember model relation properties within routes and controllers?

Currently using ember 2.7.0, I am facing an issue while setting up my ember app with a currentUser.organization derived from the authenticated token. Although I can successfully resolve the currentUser, I am encountering difficulties in resolving the prope ...

Retrieve all records from a table using Prisma client

I need to retrieve all data from a table using Prisma. How can I achieve this? (SELECT * FROM application) const applications = prisma.application.findMany({ // Retrieves all fields for the user include: { posts: { ...

Tips for centralizing error handling in Vue.js components

Within my component, I frequently use axios with then().catch() where I always include console.error() in the catch block like this: axios.get( //... ).then( //... ).catch( error => { console.error(..) } ) In addition to these instances, there a ...

Tips for Accessing Values in a Dynamic Array in Vue.js

ArrayOrdered :[ { name :"PRODUCT 1", price :"20", amount:"10", Total 1:" ", discount : "" , Total 2:" " }, { name :"PRODUCT 2", price :"50", amount:"20", Total 1:" ", discount : "" , Total 2:" " }, { name :"PRODUCT 3", price :"15.5", amount:"10", Total ...

Error: Module not found - Unable to locate 'dropzone'

Since migrating from Angular 4.4 to Angular 8.0, I encountered the following issue: ERROR in ./src/attributes/import/import.component.ts Module not found: Error: Can't resolve 'dropzone' in 'C:....\src\attributes\imp ...

Is there a way to iterate through two arrays simultaneously in React components?

Recently delving into the world of React, I am utilizing json placeholder along with axios to fetch data. Within my state, I have organized two arrays: one for posts and another for images. state = { posts : [], images : [] ...

Retrieve information from an external JSON file and display it in a jstree

I am trying to pass JSON data to a jstree object from an external file. The code snippet I have does not seem to be working properly. <script> $.jstree.defaults.core.themes.responsive = true; $('#frmt').jstree({ plugins: [" ...

What could be causing the template UI to not display the Vue data?

As someone new to Vue, I have defined my Vue code in the following way: import Vue from "vue"; export default Vue.extend({ data: () => { message: "show message"; }, }); <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js ...

Set the class of an element dynamically using ng-class and detect changes with ng-change

I want the input field to initially have the class .form-control-error. When the user clicks on the field and starts typing, I would like it to change to .form-control-success. I attempted the following code but couldn't get it to update. The ng-chan ...

Create specification for the properties of the child component

I am interested in working with the props of a parent element's children and validating those props. Can I achieve this using prop-types? export default function MyComponent(props) { return ( <div> {React.Children.map(props.chil ...

Tips on gathering information from an HTML for:

After encountering countless programming obstacles, I believe that the solution to my current issue is likely a simple fix related to syntax. However, despite numerous attempts, I have been unable to resolve it thus far. I recently created a contact form ...

Tips for achieving a stable Vuetify configuration

Working on a project using vue 2 and vuetify, initially everything was going smoothly. However, after some usage, I encountered the following error: Module not found: Error: Can't resolve 'vuetify/src/stylus/app.styl' in '/Users/marce ...

Sending an HTTP post request with form data and various field controls will not be directed to a Java backend

Recently, I've started working with AngularJs and I'm facing an issue with uploading image files along with their labels through a Jax-RS post rest API. My problem is that the control in my AngularJS controller is not entering the Java post API. ...

What is the best way to include a &nbsp; in a map function using JavaScript?

A challenge I encountered while working in React is as follows: <Grid item> { rolePriorities.map((rp, index) => ( <Chip key={index} label={rp} color="primary" sx={{ color: "whitesmoke" }} /> ...

Is there a term in JavaScript that denotes an object that can be serialized into JSON format?

Can you help me find a term for basic objects that accentuates their simplicity? Particularly, objects that do not reference themselves and do not have any methods or bindings (i.e. JSON-serializable). The terms I am currently using are: "flat object" " ...

Information is inaccessible beyond onBeforeMount in the Composition API of Vue 3

In my code snippet block, I have the following code: <script setup lang="ts"> import ApiService from '../service/api' import { reactive, onBeforeMount } from 'vue' let pokemons = reactive([]) onBeforeMount(async ()=> ...