Reputation: 1875
getGrades() {
let grades = {};
this.state.courses.map((course) => {
this.state.studentDetails.map((student) => {
request.get(`http://localhost:8080/user/${student.id}/grades`).then((response) => {
if (response) {
response.body.map((grade) => {
grades[`${student.id}_${course.id}_${grade.gradeType}`] = grade.grade;
});
}
});
});
});
this.setState({grades: grades});
}
I want that this.setState({grades: grades});
is only called when if all the information is gathered. How can I do this?
Upvotes: 1
Views: 75
Reputation: 41
you may use async-waterfall
write both activity as a function one giving parameter to other , in your case set the array if there is a responce and pass it to the next function where you set the state
https://www.npmjs.com/package/async-waterfall
Upvotes: 0
Reputation: 22872
You need to do it in opposite order.
-
getGrades() {
const onComplete = (response) => {
if (response) {
const grades = {};
this.state.courses.map((course) => {
this.state.studentDetails.map((student) => {
response.body.map((grade) => {
// Not sure this will work after you receive multiple details.
// Probably it will require some changes
grades[`${student.id}_${course.id}_${grade.gradeType}`] = grade.grade;
});
});
});
this.setState({grades: grades});
}
}
// Get IDs of students you need to fetch detail for.
const studentIds = this.state.studentDetails.map(student => student.id);
// Fetch details for all students.
// You have to implement endoint that responds with multiple students details if requested.
// E.g:
// Single detail /users/1/grades
// Multiple details /users/1,2,3/grades
request.get(`http://localhost:8080/user/${studentIds.join(',')}/grades`).then(onComplete);
}
Upvotes: 1