Notify API every minute without relying on user reload
P粉937382230
P粉937382230 2024-03-31 14:34:11
0
1
469

This is what I have now. On my Mount() I have fetchCoins() but this causes the API

to be called whenever the user refreshes

I'm trying to call the API, the data is stored in local storage, and then get 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);
    },
}

P粉937382230
P粉937382230

reply all(1)
P粉493534105

You need to keep track of the date the last fetch occurred in localStorage. Here is an example implementation:

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

           this.scheduleNextFetchCoins();
       }, nextCall)
   }

You need to change the call to this.fetchCoins() in the mounted function.

But please keep in mind that there are some caveats about this code snippet (beyond the scope of the question):

  • setTimeout and setInterval are not completely accurate time functions. They may be delayed by a few milliseconds. If you're worried about this kind of error, take a look at some other questions that propose solutions, such as this.
  • This code snippet only applies to a single instance of the component. Creating multiple components will cause a race condition in writing coin-info-last-fetch.
  • Nothing can stop the fetch loop, even if the component is destroyed. You need to store the timeout ID returned by setTimeout in the component's data so that you can eventually clear it.
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template