How to prevent connection loss in React Native?

Viewed 165

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

1 Answers

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);
}

}
Related