Trying to just call API every minute, not when user reloads

Viewed 47

This is what I have right now. On my mounted() I have fetchCoins() but that makes it so whenever a user refreshes, the API is called

I'm trying to make it so the API is calledthe data is stored in localstorage, then getting 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);
    },
}
1 Answers

You need to keep track in localStorage about the date when the last fetch happened. 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 for this one.

But keep in mind that there are a couple of caveats about this snippet (out of the scope of the question):

  • setTimeout and setInterval are not not totally accurate time functions. They could be delayed by some milliseconds. If you are concerned about this innacuracy, have a look at some other questions that propose solutions such as this one.
  • This snippet works only for a single instance of the component. Creating multiple components will result in a race condition to write into coin-info-last-fetch.
  • There's nothing stopping the loop of fetching, not even when the component is destroyed. You need to store the timeout id returned by setTimeout in the data of the component to be able to eventually clear it.
Related