react-native: app state goes on an infinite loop while listening for changes with appState on android

Description

I have implemented AppState to listen for the app state and then do certain tasks when the app either goes foreground or background. Specifically, I am doing two actions on app state change.

  1. When the app is in the foreground, I am checking if the user may have toggled permission back on so I can react properly.
  2. When the app is in a background mode, I dispatch an action to turn a flag on so when the user opens the app they will be prompted by an authentication screen to verify themselves with biometrics.

The first option works pretty well, but when I added the dispatch action inside the handler to turn the flag on, the app state keeps changing again and again and the app state goes on an infinite loop.

React Native version:

System:
    OS: macOS 10.15.7
    CPU: (8) x64 Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz
    Memory: 114.68 MB / 8.00 GB
    Shell: 5.7.1 - /bin/zsh
  Binaries:
    Node: 14.6.0 - /usr/local/bin/node
    Yarn: Not Found
    npm: 6.14.6 - /usr/local/bin/npm
    Watchman: 4.9.0 - /usr/local/bin/watchman
  Managers:
    CocoaPods: 1.9.1 - /usr/local/bin/pod
  SDKs:
    iOS SDK:
      Platforms: iOS 13.6, DriverKit 19.0, macOS 10.15, tvOS 13.4, watchOS 6.2
    Android SDK: Not Found
  IDEs:
    Android Studio: 4.0 AI-193.6911.18.40.6821437
    Xcode: 11.6/11E708 - /usr/bin/xcodebuild
  Languages:
    Java: 14.0.2 - /usr/bin/javac
    Python: 3.7.6 - /Users/amiinamo/.pyenv/shims/python
  npmPackages:
    @react-native-community/cli: Not Found
    react: ~16.11.0 => 16.11.0 
    react-native: ~0.62.2 => 0.62.2 
  npmGlobalPackages:
    *react-native*: Not Found

Steps To Reproduce

Provide a detailed list of steps that reproduce the issue.

  1. Implemented AppState and subscribed to state changes with async function for handling app state change.
  2. Added redux action to the handler.
  3. Apps state keep changing and goes to an infinite loop which even forces the app to open and come back to the foreground while in the background.

Expected Results

I expected the app to only change the state when opening the app, leaving the app, or transitioning between foreground & background which only works for IOS.

Snack, code example, screenshot, or link to a repository:

  const appState = useRef(AppState.currentState);
  const [appStateVisible, setAppStateVisible] = useState(appState.current);

  useEffect(() => {
    AppState.addEventListener('change', checkPermissions);

    return () => {
      AppState.removeEventListener('change', checkPermissions);
    };
  }, []);

  const checkPermissions = async nextAppState => {
    // just an async function that reacts to any permission changes while on background.
    await checkMultiplePermissions(saveMultiplePermissionAccess, permissions);

    if (nextAppState === 'background') {
      // an action to save the app state on redux store when the app goes background. this is the flag
      dispatch(saveAppState(true));
    }
    appState.current = nextAppState;
    setAppStateVisible(appState.current);
  };

About this issue

  • Original URL
  • State: open
  • Created 4 years ago
  • Reactions: 14
  • Comments: 22

Most upvoted comments

@shomatz not sure if it helps but for me it was because I was requesting app permissions on Android and every time AppState changed I requested them again. But I wasn’t aware that AppState changes to background while Android is requesting a permission (not the behaviour on iOS).

Once I accounted for this, I fixed my infinite loop.

I fixed the problem with this source code below;

const isPermissionFetching = useRef(false);
...
const handlerAppStateChange = async (nextAppState: AppStateStatus) => {
    if (nextAppState === 'active' && !isPermissionFetching.current) {
      console.log('App has come to the foreground!');
      isPermissionFetching.current = true;
      await checkApplicationPermissions();
      isPermissionFetching.current = false;
    }
  };

  useEffect(() => {
    const subscription = AppState.addEventListener(
      'change',
      handlerAppStateChange,
    );

    return () => {
      subscription.remove();
    };
  }, []);
...

@anastasia-iteric if your AppState is “close” to a permissions request eg. check for location permission everytime the app comes to the foreground via AppState then the underlying native request for permissions will put the app in the background for a fraction of a second and then bring it back to the foreground. As you can see, we get an infinite loop here.

Had the same issue, as others have said, Android devices go to background when requesting permission. With the help of this comment request permission always returns denied I was able to solve the infinite loop, here is my code, hope it helps someone:

const [permissionResponse, setPermissionResponse] = useState<Location.LocationPermissionResponse>();
	const appState = useRef(AppState.currentState);

	useEffect(() => {
		requestPermissionAndExecute(passMethodToBeExecuted);
		const appStateSubscription = AppState.addEventListener('change', handleAppStateChange);

		return () => {
			appStateSubscription.remove();
		}
	}, []);

	const requestPermissionAndExecute = async (callback: () => void) => {
		const permissionResponse = await Location.requestForegroundPermissionsAsync();
		setPermissionResponse(permissionResponse);
		if (permissionResponse.granted) {
			callback();
		}
	}

	const handleAppStateChange = async (nextAppState: AppStateStatus) => {
		if (nextAppState === appState.current) return;

		const isTransitioningToForeground = appState.current.match(/inactive|background/) && nextAppState === 'active';

		if (isTransitioningToForeground) {
			await requestPermissionAndExecute(passMethodToBeExecuted);
		} else {
			// App went to background
		}

		appState.current = nextAppState;
	}

The main problem for me was that I wasn’t checking for this conditional appState.current.match(/inactive|background/), but was doing only this nextAppState === 'active'

Also I had to do await when calling requestPermissionAndExecute(passMethodToBeExecuted) inside handleAppStateChange method.

That fixed it for me

This seems to be happening in our case as well. The app goes in an infinite loop only on Android (specifically, it seems to happen only in Android 10), but we already took care of the permissions. When we remove the event listener the loop never happens. Also, it happens only when we dispatch a redux action after making a HTTP request inside the handler function.

We are using react-native 0.63.2. We already tried upgrading to the latest version but the issue is still present.