试图每分钟一次调用API,而不是在用户重新加载时

发布于 2025-01-31 18:52:46 字数 815 浏览 0 评论 0原文

这就是我现在拥有的。 在我的安装()上,我有fetchcoins(),但是每当用户刷新用户时,API被称为

我试图制作它,因此API称为数据,然后每分钟存储数据,然后每分钟获取数据

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);
    },
}

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);
    },
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

满意归宿 2025-02-07 18:52:46

您需要在LocalStorage中跟踪最后一次提取的日期。这是一个示例实现:

   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)
   }

您需要将呼叫更改为this.fetchcoins()已安装的函数中。

但是请记住,有关此片段有几个警告(出于问题的范围):

  • settimeoutsetInterval并不是完全准确的时间函数。它们可能会被一些毫秒拖延。如果您担心这种无关,请查看一些其他问题,这些问题提出了解决方案,例如这个
  • 该片段仅适用于组件的一个实例。创建多个组件将导致竞赛条件写入coin-info-last-fetch
  • 没有什么可以阻止提取的循环,即使在组件被摧毁时也没有。您需要将settimeout返回的超时ID存储在组件的数据中,以最终清除它。

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.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文