From ed42c228f83d6382d7153c474789914f56655add Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kent=20Cederstr=C3=B6m?= Date: Mon, 11 Jun 2018 11:25:56 +0200 Subject: [PATCH] Adds ability to check for connectivity in background, defaults to false (#97) --- README.md | 3 +++ src/withNetworkConnectivity.js | 7 ++++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 9c5a8c84..f6b2eab9 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,7 @@ type Config = { pingServerUrl?: string = 'https://google.com', withExtraHeadRequest?: boolean = true, checkConnectionInterval?: number = 0, + checkInBackground?: boolean = false, } ``` @@ -90,6 +91,8 @@ type Config = { `checkConnectionInterval`: the interval (in ms) you want to ping the server at. The default is 0, and that means it is not going to regularly check connectivity. +`checkInBackground`: whether or not to check connectivity when app isn't active. Default is `false`. + ##### Usage ```js import React from 'react'; diff --git a/src/withNetworkConnectivity.js b/src/withNetworkConnectivity.js index 06f980b3..7684cc73 100644 --- a/src/withNetworkConnectivity.js +++ b/src/withNetworkConnectivity.js @@ -2,7 +2,7 @@ import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; -import { NetInfo, Platform } from 'react-native'; +import { NetInfo, Platform, AppState } from 'react-native'; import hoistStatics from 'hoist-non-react-statics'; import { connectionChange } from './actionCreators'; import reactConnectionStore from './reactConnectionStore'; @@ -18,6 +18,7 @@ type Arguments = { pingServerUrl?: string, withExtraHeadRequest?: boolean, checkConnectionInterval?: number, + checkInBackground?: boolean, }; type State = { @@ -31,6 +32,7 @@ const withNetworkConnectivity = ( pingServerUrl = 'https://google.com', withExtraHeadRequest = true, checkConnectionInterval = 0, + checkInBackground = false, }: Arguments = {}, ) => (WrappedComponent: ReactClass<*>) => { if (typeof withRedux !== 'boolean') { @@ -100,6 +102,9 @@ const withNetworkConnectivity = ( }; checkInternet = () => { + if (checkInBackground === false && AppState.currentState !== 'active') { + return; // <-- Return early as we dont care about connectivity if apps' not in foreground. + } checkInternetAccess( timeout, pingServerUrl,