How to prevent socket.io from disconnecting when react native app is in background/device is lock?
After doing some reading online, the reason my socket server will determine my react native app is 'dead' is because all of the javascript code inside my app has stopped working when my device is locked or in background.
Therefore, i have figured out a solution to solve this problem.
Tools i have used:
- React Native Appstate
- React Native Background Timer
My client side code:
import React, {useEffect, useRef} from 'react';
import {AppState} from 'react-native'
export default () => {
const appState = useRef(AppState.currentState);
var interval
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(()=>{
console.log('connection status ', socket.connected)
socket.emit('online')
},5000)
appState.current = nextAppState;
console.log("AppState", appState.current);
}
useEffect (() => {
AppState.addEventListener("change", _handleAppStateChange);
return () => {
AppState.removeEventListener("change", _handleAppStateChange);
};
},[])
}
My Server side code:
io.on('connection',(socket)=>{
socket.on('online',()=>{
//do nothing
})
}
)
This solution works on my app. Now socket will not disconnect until i close the app or click disconnect button.