I am trying to record audio using an expo react native application.
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?
I added my code on snack.expo like suggested.The code is resulting in the same undefined error when clicking the start record button as when runnig it locally.
Uncaught (in promise) TypeError: Cannot read property 'startRecorder'of undefined
Here is some modified react
code which seems to work.The original code above on snack.expo 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>