Created
February 21, 2018 19:45
-
-
Save hilkeheremans/53bfacd79160bbb522d4793d9d3783c3 to your computer and use it in GitHub Desktop.
React and React Native Gists
This file contains 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
import { AppState } from 'react-native' | |
export const AppStateTypes = { | |
APP_RESUMED: '@appstate/RESUMED', | |
APP_BACKGROUNDED: '@appstate/BACKGROUNDED', | |
APP_INACTIVE: '@appstate/INACTIVE' | |
} | |
/** | |
* Store Enhancer that injects app state actions whenever the app state changes | |
*/ | |
export default () => createStore => (...args) => { | |
const store = createStore(...args) | |
// hook into RN AppState | |
AppState.addEventListener('change', handleAppStateChange) | |
let currentState = AppState.currentState | |
function handleAppStateChange (newAppState) { | |
if (currentState !== newAppState) { | |
let type | |
if (newAppState === 'active') { | |
type = AppStateTypes.APP_RESUMED | |
} else if (newAppState === 'background') { | |
type = AppStateTypes.APP_BACKGROUNDED | |
} else if (newAppState === 'inactive') { | |
type = AppStateTypes.APP_INACTIVE | |
} | |
if (type) { | |
store.dispatch({ | |
type | |
}) | |
} | |
} | |
currentState = newAppState | |
} | |
return store | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment