I define a method in a React class component as follows
onSaveAudio = (e) => {
e.preventDefault();
const { audioBlob } = this.state;
let reader = new FileReader();
reader.onloadend = function () {
const base64 = reader.result;
const bstr = base64.split(',')[1];
console.log(bstr);
console.log('this.props', this.props);
this.props.onSaveAudio(bstr);
}
reader.readAsDataURL(audioBlob);
}
At the console.log('this.props', this.props) line, it's printing "undefined"; at the this.props.onSaveAudio line, an error is thrown:
Uncaught TypeError: Cannot read property 'onSaveAudio' of undefined at FileReader.reader.onloadend (recorder.js:300)
My understanding is that "onloadend" is triggered after the "reader" finishes reading "audioBlob". I need to call the this.props.onSaveAudio in the "onloadend" function, because if I call it outside of "onloadend", I can't time the call to after the reading finishes and "reader.result" is ready, and "bstr" would resolve to undefined with the wrong timing; but if I call the this.props.onSaveAudio within "onloadend", then "this" is not recognized. Seems to be a dilemma.
My guess is I need a solution to either bind "this" within "onloadend", or be able to somehow time a this.props.onSaveAudio call outside of the "onloadend" function, after the "onloadend" function finishes execution.
Any advice?
One way I found is to use an arrow function when defining "reader.onloadend".
reader.onloadend = () => {
const base64 = reader.result;
const bstr = base64.split(',')[1];
console.log(bstr);
console.log('this.props', this.props);
this.props.onSaveAudio(bstr);
}
this.props will be defined in this case