I have the following ES6 code:
export default class HomePage extends Component {
constructor(props) {
super(props);
this.state = {
itemsWithData: []
};
this.details = [1, 2, 3] ;
}
loadDetails = items => {
items.forEach(item => {
axios
.get(item.url)
.then(response => {
this.details = response.data;
})
.catch(e => {
console.warn(`Error while getting ${item.name} details`);
});
});
console.log(this.details);//It prints [1,2,3]
};
}
As you can see, I'm setting this.details
inside then
.I've logged the this.details
inside then
just to make sure it sees the class context. It indeed does. But somehow, setting the details seems to have no effect at the function end. It prints the old value. The response returned from the request has absolutely different data each time. So it's never [1,2,3]. What should I do to get the details data changed appropriately? Is it something to do with async-await?
P.S. In fact, the content of the arrow function passed to then
is this:
this.details[item.name]=response.data;
So, I'm not stupidly setting details to a new value at each turn.