AppState on Expo client remains active

  1. SDK Version: 37.0.0
  2. Platforms(Android/iOS/web/all): Android

I am trying to call a function when AppState changes to active. However I am noticing that, whether the app is in the background or not, I am getting an ‘active’ appstate:

// AppState change hook

  useEffect(() => {

    AppState.addEventListener("change", _handleAppStateChange);

    return () => {

      AppState.removeEventListener("change", _handleAppStateChange);

    };

  }, []);

  const _handleAppStateChange = (nextAppState) => {

    console.log("appState: ", appState);

    if (appState.match(/inactive|background/) && nextAppState === "active") {

      console.log(">> App has come to the foreground! <<");

      _validateCheckInDistance();

      _validateTimePeriod();

    }

    setAppState(nextAppState);

  };

appState: active

This is very peculiar, and not sure what I am doing wrong. I am testing this using the Expo app on my Android phone (through metro tunnel).

2 Likes

I have exactly the same behaviour on iOS simulator.
setAppState(nextAppState) doesn’t change the value of appState !
This is the way I solved the issue (AppState issue - Snack)

import React, { useEffect, useState } from "react";
import { AppState, StyleSheet, Text, View } from "react-native";

const AppStateExample = () => {
  const [appState, setAppState] = useState(AppState.currentState);

  useEffect(() => {
    const _handleAppStateChange = nextAppState => {
    console.log("_handleAppStateChange", nextAppState);
    if (appState.match(/inactive|background/) && nextAppState === "active") {
      console.log("App has come to the foreground!");
    }
    setAppState(nextAppState);
  };

    AppState.addEventListener("change", _handleAppStateChange);

    return () => {
      AppState.removeEventListener("change", _handleAppStateChange);
    };
  }, [appState]);

  
  console.log("appState", appState);
  return (
    <View style={styles.container}>
      <Text>Current state is: {appState}</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center"
  }
});

export default AppStateExample;

The log displays what is expected in snack’s or expo cli :

iPhone 8: appState inactive
iPhone 8: _handleAppStateChange inactive
iPhone 8: _handleAppStateChange background
iPhone 8: appState background
iPhone 8: App has come to the foreground!
iPhone 8: appState active
2 Likes

I used useRef instead of useState to store the AppState and it works like a charms!!!

@amarin can you please detail your solution on a snack ?

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.