Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent connection loss in React Native?

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

like image 381
MK_Pierce Avatar asked Sep 07 '25 04:09

MK_Pierce


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

}
like image 159
Awais Ibrar Avatar answered Sep 09 '25 22:09

Awais Ibrar