UNPKG

@appello/mobile

Version:

Common package with many useful features for mobile development

29 lines (28 loc) 1.51 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useAppState = exports.APP_STATE_BACKGROUND = exports.APP_STATE_INACTIVE = exports.APP_STATE_ACTIVE = void 0; const react_1 = require("react"); const react_native_1 = require("react-native"); exports.APP_STATE_ACTIVE = 'active'; exports.APP_STATE_INACTIVE = 'inactive'; exports.APP_STATE_BACKGROUND = 'background'; const useAppState = (props = {}) => { const { onChange, onForeground, onBackground } = props; const [appState, setAppState] = (0, react_1.useState)(react_native_1.AppState.currentState); (0, react_1.useEffect)(() => { const appStateListener = react_native_1.AppState.addEventListener('change', nextAppState => { if (nextAppState === exports.APP_STATE_ACTIVE && appState !== exports.APP_STATE_ACTIVE) { onForeground === null || onForeground === void 0 ? void 0 : onForeground(); } else if (appState === exports.APP_STATE_ACTIVE && [exports.APP_STATE_BACKGROUND, exports.APP_STATE_INACTIVE].includes(nextAppState)) { onBackground === null || onBackground === void 0 ? void 0 : onBackground(); } setAppState(nextAppState); onChange === null || onChange === void 0 ? void 0 : onChange(nextAppState); }); return () => appStateListener.remove(); }, [onChange, onForeground, onBackground, appState]); return appState; }; exports.useAppState = useAppState;