Created
January 30, 2021 17:37
-
-
Save ahartzog/9b07e3661c7b8a94da09d96b58e60d24 to your computer and use it in GitHub Desktop.
React Native Detect Network Status
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example config from https://medium.com/@kulor/creating-an-offline-first-react-native-app-5534d7794969 | |
import Config from 'modules/config'; | |
import agent, { buildUrl } from 'modules/agent'; | |
let online = true; | |
let timer = null as null | NodeJS.Timer; | |
const clearTimer = () => { | |
if (timer) { | |
clearInterval(timer); | |
timer = null; | |
} | |
}; | |
const updateStatus = (isOnline: boolean, callback: any): void => { | |
online = isOnline; | |
callback({ | |
online, | |
}); // Tell redux-offline that our status changed | |
const interval = isOnline | |
? Config.API_PING_ONLINE_INTERVAL | |
: Config.API_PING_OFFLINE_INTERVAL; | |
clearTimer(); | |
timer = setInterval( | |
() => checkNetworkStatus(callback), | |
Number.parseInt(interval, 10), | |
); | |
}; | |
const checkNetworkStatus = async (callback: any) => { | |
try { | |
await agent.post('Register/ping'); | |
// Success, update our status | |
if (!online) { | |
console.devLog.info('detectNetwork change: Online'); | |
updateStatus(true, callback); | |
} | |
} catch (e) { | |
// Something wrong, we are not offline | |
if (online) { | |
console.devLog.info('detectNetwork change: Offline'); | |
updateStatus(false, callback); | |
} | |
} | |
}; | |
const detectNetwork = (callback: any): void => { | |
updateStatus(true, callback); | |
}; | |
export default detectNetwork; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment