react-nativesettimeoutcleartimeout

React Native setTimeout - How to clearTimeout


I have a setTimeout call outside of useEffect, how do I clearTimeout when the screen unmounts?

For instance, I have a functional component with this in it...

...

useEffect(() => {
  return () => clearTimeout(myTimeout)
}, [])

_getData = () => {
  fetch()
  .then(data => {
    let myTimeout = setTimeout(() => setSomething(!something), 5000)
  })
}

So somewhere later in the code I call _getData() - I do not want this to run with useEffect when the page first loads, only when certain action is taken. After I get the data I set the timeout. But the useEffect is not aware of this timeout.

I have tried setting the timeout like this...

_getData... 
  setTimeoutVar(setTimeout(() => setSomething(!something), 5000))

useEffect...
 return () => clearTimeout(setTimeoutVar)

I have tried a few other weird ideas, nothing is working, I can't figure this one out.

Thoughts?


Solution

  • All day working on this - write a question on stackoverflow and figure it out in two minutes. Crazy!

    The answer to this question is to set a variable to false, then, change the variable when you get the data back. Then have a separate useEffect() function that only deals with this. When the variable changes it runs. If the variable is true - sets the timeout and the useEffect function returns the clearTimeout...

    const [refresh, setRefresh] = useState(false)
    
    useEffect(() => {
      let timeoutVariable
    
      if(refresh){
        timeoutVariable = setTimeout(() => setRefresh(false), 5000)
      }
    
      return () => clearTimeout(timeoutVariable)
    
    }, [refresh]) 
    
    _getData = () => {
      fetch()
      .then(data => {
        setRefresh(true)
      })
    }