I have the following working code:
fetchPost (id) {
var mainObject = {},
toReturn = [],
promises = [];
var that = this;
for(var i=id; i<10; i++) {
promises.push(axios.get(`api/posts/${i}`));
}
axios.all(promises).then(function(results) {
results.forEach(function(response) {
toReturn.push(response.data);
console.log("toReturn: " + toReturn);
that.setState({ post: toReturn });
});
});
}
but to get it working I had to add var that = this;
so that that.setState
would work.
Using this.setState
would generate this error:
Uncaught (in promise) TypeError: Cannot read property 'setState' of undefined
So why do I have to use this hack that I don't understand to get this sample code to work? It doesn't make any sense to me.