I have a setInterval that keeps running even when you close (not quit) the app. I would like to call a function when my app is closed or the device is put to sleep so that it clears the setInterval.
3 Answers
itinance was close. The answer is actually to use
AppState.addEventListener('change', state => {
if (state === 'active') {
// do this
} else if (state === 'background') {
// do that
} else if (state === 'inactive') {
// do that other thing
}
});
4 Comments
Mr. Robot
This is only on iOS, doesnt work on Android
SeanMC
this does not fire when you close the app, only when you minimize it or change apps
Zeeshan
did anyone find solution? 1) for android 2) does not fire when app close?
Mo W.
Is the callback in
addEventListener running in react context then or outside of it? So basically, do I still have access to hooks?AppState is your friend! Have a look at the documentation of AppState.
So in your component, where the setTimeout exists, just require AppState and add an event listener like this:
AppState.addEventListener('background', this.handlePutAppToBackground);
AppState.addEventListener('inactive', this.handlePutAppToBackground);
handlePutAppToBackground() would be now a method in your component, where you would call clearTimeout(...)
2 Comments
SeanMC
docs for AppState include no mention of closing the app. When you minimize the app, or change apps, it runs the
background state -which handles that AppState. If you "close" an app -AppState fires no changesMuhammad Rafeh Atique
does not works!
I solved this issue by adding useEffect() without dependencies to the component where i want to emit a certain event when the component unmounts for any reason and in the clean up function emit the desired function.
useEffect(() => {
return () => {
The desired function
}
})