0

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.detailsinside 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.

Mikayil Abdullayev
  • 12,117
  • 26
  • 122
  • 206
  • arrow functions don't have `this` so you need to use the oldskool `function(){}` instead – bdbdbd Nov 02 '19 at 18:43
  • 1
    @bdbdbd No this is fine, he wants to inherit the scope of this from the parent class, which he is doing fine in this example. – Jon Warren Nov 02 '19 at 18:45
  • I know they don't have it. But I also know that they refer to the outtermost non arrow function context. Don't they? – Mikayil Abdullayev Nov 02 '19 at 18:45
  • This has nothing to do with your arrow functions referring to the wrong context. The problem is that they are running at the wrong time - asynchronously, after you had logged the old value. – Bergi Nov 02 '19 at 18:57
  • In fact I've tried to wait for the axios get response by doing like this: `const response = await axios.get(url); this.details = response.data;` But still it didn't help. I of cource made the out arrow function (that of the forEach function) async. – Mikayil Abdullayev Nov 02 '19 at 19:05
  • I tried to go Promise.all way but that did not meet my needs, as inside each promise resolve iteration I need to access the current array item property. I eventually switched to normal for loop from for each by – Mikayil Abdullayev Nov 02 '19 at 20:51

0 Answers0