I'm learning about VUE and i have a simple request in an API that gives me infos about prices of the bitcoins. I'd like to update the table every second and i wonder how to do it in the easiest way. Here is my simple code
async mounted() {
const res = await fetch(
"https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&parkline=false"
);
const data = await res.json();
this.coins = data;
this.filteredCoins = data;
}
I'd like to do this request and update the table in my screen every second pls.
CodePudding user response:
Use setInterval
and a lambda function to capture the this
context. In another unmount hook, you might want to clear the interval timer.
async mounted() {
const doFetch = ()=> {
const res = await fetch(
"https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&parkline=false"
);
const data = await res.json();
this.coins = data;
this.filteredCoins = data;
}
setInterval(doFetch, 1000)
}
CodePudding user response:
you can define an interval to fetch data every second like this:
export default {
data () {
return {
coins: [],
filteredCoins: []
}
},
mounted() {
setInterval(this.getData, 1000)
},
methods: {
async getData() {
const res = await fetch(
'https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&parkline=false'
);
const data = await res.json();
this.coins = data;
this.filteredCoins = data;
}
}
}