This is what I have now. On my Mount() I have fetchCoins() but this causes the API
to be called whenever the user refreshesI'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粉4935341052024-04-01 13:42:48
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. coin-info-last-fetch
. setTimeout
in the component's data so that you can eventually clear it.