react-native-appstate-hook
react-native-appstate-hook copied to clipboard
TypeError: undefined is not an object (evaluating 'appState.remove')
node_modules/react-native-appstate-hook/dist/index.js
`import { useState, useEffect } from 'react'; import { AppState } from 'react-native';
export default function useAppState(settings) { const { onChange, onForeground, onBackground } = settings || {}; const [appState, setAppState] = useState(AppState.currentState);
useEffect(() => { function handleAppStateChange(nextAppState) { if (nextAppState === 'active' && appState !== 'active') { isValidFunction(onForeground) && onForeground(); } else if (appState === 'active' && nextAppState.match(/inactive|background/)) { isValidFunction(onBackground) && onBackground(); } setAppState(nextAppState); isValidFunction(onChange) && onChange(nextAppState); } const appState = AppState.addEventListener('change', handleAppStateChange);
// removing -> return appState.remove(); return; }, [onChange, onForeground, onBackground, appState]);
// settings validation function isValidFunction(func) { return func && typeof func === 'function'; } return { appState }; }`
Interim solution!
Same problem occur after upgrade to react native 0.64
0.64 have a small difference, The solution is create the hook by ourself as it is simple, :).
We're on React Native 0.64.3 (Expo), and it looks like AppState.addEventListener
is not returning an EventSubscription. It looks like that first appears in RN 0.65. In the meantime, we're doing this in a custom hook:
function isValidFunction(func) {
return func && typeof func === "function";
}
export const useAppState = (settings) => {
const { onChange, onForeground, onBackground } = settings || {};
const [appState, setAppState] = useState(AppState.currentState);
useEffect(() => {
const handleAppStateChange = (nextAppState) => {
if (nextAppState === "active" && appState !== "active") {
isValidFunction(onForeground) && onForeground();
} else if (
appState === "active" &&
nextAppState.match(/inactive|background/)
) {
isValidFunction(onBackground) && onBackground();
}
setAppState(nextAppState);
isValidFunction(onChange) && onChange(nextAppState);
}
AppState.addEventListener("change", handleAppStateChange);
return () => {
AppState.removeEventListener("change", handleAppStateChange);
};
}, [onChange, onForeground, onBackground, appState]);
return { appState };
};