For loop and axios I have following scenario where I have to call a third party API for each item in Vue object. I call it as follows:
var $this = this;
for (var i = 0; i < $this.items.length; i++) {
axios.get('https://thirdpartyapi.com/api/' + $this.items[i].somevalue)
.then(function(response) {
if (somevarialble.toLowerCase() == response.data[0].itemValue.toLowerCase()) {
$this.filteredItems.push($this.items[i]);
}
})
.catch(function(error) {
console.log(error);
});
}
But I always get i as 62(which is the last one). How to pass i inside axios?
Maybe you could use
this.items.forEach((item) => { axios.get('https://thirdpartyapi.com/api/' + item.somevalue) .then(function(response) { if (somevarialble.toLowerCase() == response.data[0].itemValue.toLowerCase()) { $this.filteredItems.push(item); } }) .catch(function(error) { console.log(error); }); })
Make i in the parent scope and use function(response, i) for the index. The you could use it in your block. Also, you may want to clean up your code and use a feature axios has called concurrency with axios.all(). You can look it over here https://github.com/axios/axios
Please sign in or create an account to participate in this conversation.