Skip to content

Instantly share code, notes, and snippets.

@hilkeheremans
Created February 21, 2018 19:45
Show Gist options
  • Save hilkeheremans/53bfacd79160bbb522d4793d9d3783c3 to your computer and use it in GitHub Desktop.
Save hilkeheremans/53bfacd79160bbb522d4793d9d3783c3 to your computer and use it in GitHub Desktop.
React and React Native Gists
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