简体   繁体   中英

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM