Home Passing Variable to Asynchronous JavaScript Function Invoked in Loop (React)
Reply: 2

Passing Variable to Asynchronous JavaScript Function Invoked in Loop (React)

Bob Dole
1#
Bob Dole Published in 2018-01-11 01:11:33Z

I'm writing some JavaScript code for my React project. The code loads a series of images, then updates the state with the dimensions of each image. The problem is that when I invoke the onload function, the this keyword refers to the object attached to the onload. This means I can no longer access props through this.props. Is there a way to pass the props into the function?

Here's my code:

for (var i = 0; i < a; i++) {

  var path = i + ".jpg";
  imgArray[i].index = i;

  imgArray[i].onload = function() {
    this.props.actions.updateImage(this.index, this.width, this.height);
  }

  imgArray[i].src = path;
}

I currently get an error, as this.props is undefined, since this refers to imgArray[i] in the function, not the global context.

nem035
2#
nem035 Reply to 2018-01-11 01:21:59Z

A simple solution might just be to save the context or props into a variable and use them:

const { props } = this;

// ...

imgArray[i].onload = function() {
  props.actions.updateImage(this.index, this.width, this.height);
}

You can also save the other context if you find that more readable:

const ctx = this;

// ...

imgArray[i].onload = function() {
  ctx.props.actions.updateImage(this.index, this.width, this.height);
}
CRice
3#
CRice Reply to 2018-01-11 02:43:59Z

Your best bet is to capture the props by using a variable that holds a reference to the outer 'this' that you access via the closure:

// This line here, now inside the function, use 'self' to refer to outer context
let self = this;
for (var i = 0; i < a; i++) {

  var path = i + ".jpg";
  imgArray[i].index = i;

  imgArray[i].onload = function() {
    // note call to self.props instead of this.props:
    self.props.actions.updateImage(this.index, this.width, this.height);
  }

  imgArray[i].src = path;
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.319821 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO