There are instances in my React Native app where a user may navigate away from the app, but then come back. While running it in Expo, if the user is away too long, they will lose connection to the server. How can I prevent/correct this? We are using a Websocket
You can implement addEventListener in use effect like this.
import {AppState} from 'react-native';
useEffect(() => {
setTimeout(() => {
AppState.addEventListener("change", _handleAppStateChange);
}, 2000);
return () => {
AppState.removeEventListener("change", _handleAppStateChange);
};
}, []);
Here you define your _handleAppStateChange
const _handleAppStateChange = (nextAppState) => {
if (
appState.current.match(/inactive|background/) &&
nextAppState === "active"
) {
console.log("App has come to the foreground!");
//clearInterval when your app has come back to the foreground
BackgroundTimer.clearInterval(interval)
}else{
//app goes to background
console.log('app goes to background')
//tell the server that your app is still online when your app detect that it goes to background
interval = BackgroundTimer.setInterval(()=>{
},100)
appState.current = nextAppState;
console.log("AppState", appState.current);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With