Here i am trying to fetch data from nested axios call. it's able get the response from two axios call.
but i am not able to update prize_pool inside 2nd axios call. can anyone help me on this
getAllLeague() {
axios.get(BASE_URL + 'leagues').then((response) => {
var arrData = [];
for(var i=0; i<response.data.length; i++) {
var data = {
"leagueid": response.data[i].leagueid,
"description": response.data[i].description,
"itemdef": response.data[i].itemdef,
"name": response.data[i].name,
"tournament_url": response.data[i].tournament_url,
"prize_pool" : ''
}
axios.get(BASE_URL + 'getTournamentPrizePool/' + response.data[i].leagueid).then((response) => {
data.prize_pool = response.data.prize_pool;
}).catch((error) => {
console.log(error);
});
arrData.push(data);
}
console.log(arrData);
this.setState({
leagueList : arrData
});
}).catch((error) => {
console.log(error);
});
}
Cause
this.setState({
leagueList : arrData
});
will run before your 2nd axios complete. Try this. Using Promise.all is more cleaner. Hope it will help you.
getAllLeague() {
axios.get(BASE_URL + 'leagues').then((response) => {
const promises = response.data.map(item => {
const formData = {
"leagueid": response.data[i].leagueid,
"description": response.data[i].description,
"itemdef": response.data[i].itemdef,
"name": response.data[i].name,
"tournament_url": response.data[i].tournament_url,
"prize_pool" : ''
}
const url = BASE_URL + 'getTournamentPrizePool/' + item.leagueid
return axios.get(url).then(res => {
return {
...formData,
prize_pool: res.data.prize_pool,
}
}).catch((error) => {
console.log(error);
})
})
Promise.all(promises).then(arrData => {
this.setState({
leagueList : arrData
});
})
}).catch((error) => {
console.log(error);
});
}
Here is the answer. need to use async and await at the time of API call in inner axios.
getAllLeague() {
axios.get(BASE_URL + 'leagues').then(async (response) => {
var arrData = [];
for(var i=0; i<response.data.length; i++) {
var data = {
"leagueid": response.data[i].leagueid,
"description": response.data[i].description,
"itemdef": response.data[i].itemdef,
"name": response.data[i].name,
"tournament_url": response.data[i].tournament_url,
"prize_pool" : ''
}
await axios.get(BASE_URL + 'getTournamentPrizePool/' + response.data[i].leagueid).then((response) => {
data.prize_pool = response.data.prize_pool;
})
arrData.push(data);
}
console.log(arrData);
this.setState({
leagueList : arrData
});
}).catch((error) => {
console.log(error);
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.