Reputation: 1512
I have a video component class that possesses a handleRecord
method. Inside the handleRecord
method, there's an object called recorder
which returns a blob the object method call called stopRecording
.
Whatever gets returned, I want the value to set state in the video component. But the this
refers to recorder object in the callback, not the component itself. What's best practice to get the component within the callback and use the recorder
object?
handleRecord() {
...
} else {
this.state.recordVideo
recorder.stopRecording(function() {
var blob = this.getBlob();
console.log(this) // <= this refers to recorder object not the component
});
}
}
Upvotes: 0
Views: 50
Reputation: 57964
You could set a variable to refer to the component, then use it inside the function:
const component = this;
recorder.stopRecording(function() {
var blob = this.getBlob();
console.log(component);
});
This will essentially capture the this
value when it does refer to the component and cache it in component
, so when you use it in the callback function this
'll refer to the recorder object, but component
will refer to your component.
Of course, you could just directly refer to the recorder
object if you would like to use something like an arrow function, which takes the this
value of its enclosing scope -- which is the component:
recorder.stopRecording(() => {
var blob = recorder.getBlob();
console.log(this) // <= this refers to component
});
Upvotes: 1