Using ReactJS, I have two different API points that I am trying to get and restructure: students
and scores
. They are both an array of objects.
I would recommend restructuring slightly - instead of updating your state after each fetch call completes, wait for both to complete and then update the state all at once. you can then use the setState
callback method to run the next method you would like to.
You can use a Promise library such as Bluebird to wait for multiple fetch requests to finish before doing something else
import Promise from 'bluebird'
getStudents = () => {
return fetch(`api/students`, {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).then(response => response.json());
};
getScores = () => {
return fetch(`api/scores`, {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).then(response => response.json());
};
Promise.join(getStudents(), getScores(), (students, scores) => {
this.setState({
students,
scores
}, this.rearrangeStudentsWithScores);
});