PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, April 20, 2022

[FIXED] How to prevent connection loss in React Native?

 April 20, 2022     amazon-web-services, connection, expo, javascript, react-native     No comments   

Issue

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


Solution

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

}


Answered By - Awais Ibrar
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing