Adam B
Adam B

Reputation: 135

Using setTimeout and accessing state is not working in React Native

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

Answers (1)

Slava Knyazev
Slava Knyazev

Reputation: 6081

Calling a setState function does two things:

  • Update the value of the state for the next render
  • Trigger a new render

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

Related Questions