I declare in one of my function component App
the constant audioRecorderPlayer
. When I try to access it in the function onStartRecord
I get the error Unhandled Rejection (TypeError): Cannot read property 'startRecorder' of undefined
pointing to the line with audioRecorderPlayer.startRecorder()
inside onStartRecord
.
How do I have to implement audioRecorderPlayer
in Typescript or ES6 to be able to access it in the onStartRecord
method and all my functions within the App
component?
const App: React.FC<Props> = (props) => { // ... // This is where I initialize the constant const audioRecorderPlayer = new AudioRecorderPlayer(); // ... const onStartRecord = () => { // Here a valid object is printed in the console featuring startRecording() console.log(audioRecorderPlayer); // Here I try to access it audioRecorderPlayer.startRecorder() .then((result: string) => { console.log(result); }); }; // ... return (<View style={styles.container}><ScrollView> <Button title='Start Recording' onPress={() => onStartRecord()}/></ScrollView></View> );}export default App;
Here is some modified code which seems to work. The Code above is not working.
class AudioRecorderPlayer { startRecorder(): Promise < string > { return new Promise((resolve) => { resolve('Success!'); }); }}interface Props { audioRecorderPlayer: AudioRecorderPlayer;}const App: React.FC < Props > = (props) => { // This is where I initialize the constant const audioRecorderPlayer = new AudioRecorderPlayer(); const onStartRecord = () => { // Here I try to access it console.log('Button clicked!') audioRecorderPlayer.startRecorder() .then((result: string) => { console.log(result); }); }; return ( <div><p> Press Button to trigger function </p> <button onClick = {() => onStartRecord()}> Start Recording </button></div> );}// Render itReactDOM.render( < App title = "My App" / > , document.getElementById("react"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script><div id="react"></div>
EDIT:
I am using expo to run the app in my browser.