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); }, }
You need to keep track of the date the last fetch occurred in localStorage. Here is an example implementation:
You need to change the call to
this.fetchCoins()
in themounted
function.But please keep in mind that there are some caveats about this code snippet (beyond the scope of the question):
setTimeout
andsetInterval
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.