Reputation: 135
I am trying to have a setTimeout function call a method that works with some state but no matter what I do, the state variable is always undefined.
// recordingObj is an instance of Expo-AV's `RecordingObject`
const [recordingObj, setRecording] = useState();
let noSpeechTimer = null;
async function startRecording() {
const { recording } = await Audio.Recording.createAsync(Audio.RecordingOptionsPresets.HIGH_QUALITY);
setRecording(recording);
noSpeechTimer = setTimeout(()=> {
console.log("NO SPEECH DETECTED")
stopRecording();
}, 5000));
}
async function stopRecording() {
await recordingObj.stopAndUnloadAsync(); // <-- Errors here. `recording` is undefined
setRecording(undefined);
...
}
I have tried setting noSpeechTimer
up with useRef()
, that didnt work. I tried creating a second variable for recordingObj and setting it up with useRef()
and then calling recordingObjRef.current.stopAndUnloadAsync()
and that didnt work. Im really stumped here as to whats happening.
Upvotes: 0
Views: 234
Reputation: 6081
Calling a setState
function does two things:
This means that the updated value from setState(value)
will not be available until the next render.
Your case can be solved with a ref:
const recordingRef = useRef(null);
// ...
recordingRef.current = recording;
// ...
if (recordingRef.current)
recordingRef.current.stopAndUnloadAsync()
recordingRef.current = null;
Upvotes: 1