react-native-appstate-hook icon indicating copy to clipboard operation
react-native-appstate-hook copied to clipboard

TypeError: undefined is not an object (evaluating 'appState.remove')

Open heluansantos-zz opened this issue 3 years ago • 2 comments

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!

heluansantos-zz avatar Nov 23 '21 20:11 heluansantos-zz

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, :).

imhazige avatar Jan 03 '22 05:01 imhazige

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 };
};

andrewastrachan avatar Mar 30 '22 16:03 andrewastrachan