react-native: AppState change doesn't fire on launch on iOS

AppState’s change event doesn’t fire on first launch on iOS, but does fire on Android. The currentState does change however because the RCTAppState.getCurrentAppState call eventually returns with the active state.

Environment

Environment: OS: macOS High Sierra 10.13.3 Node: 8.9.4 Yarn: 1.5.1 npm: 5.6.0 Watchman: 4.7.0 Xcode: Xcode 9.2 Build version 9C40b Android Studio: 3.0 AI-171.4443003

Packages: (wanted => installed) react: 16.2.0 => 16.2.0 react-native: 0.54.3 => 0.54.3

Steps to Reproduce

AppState.addEventListener('change', () => console.log('changed', AppState.currentState));
console.log('start state', AppState.currentState);
setInterval(() => {
    console.log('current state', AppState.current);
});

This prints:

start state unknown
current state unknown
current state active
current state active
current state active
...

Expected Behavior

The change handler should fire since the currentState does change from unknown to active.

Actual Behavior

change handler never fires.

To fix either:

  1. The RCTAppState.getCurrentAppState callback needs to compare currentState to appStateData.app_state and manually fire the event
  2. RCTAppState.getCurrentAppState should be removed and native side should always fire one event at startup to initialize the state, then you don’t need this separate init step either.

I’m not sure how to do (2) since it means dispatching an event always on startup, not sure where you’d put that code? (1) is easy enough change RCTAppState.getCurrentAppState to not take a callback at all and just dispatch an event instead.

RCT_EXPORT_METHOD(getCurrentAppState:(RCTResponseSenderBlock)callback
                  error:(__unused RCTResponseSenderBlock)error)
{
  callback(@[@{@"app_state": RCTCurrentAppBackgroundState()}]);
}

becomes

    [self sendEventWithName:@"appStateDidChange"
                       body:@{@"app_state": RCTCurrentAppBackgroundState()}];

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 22
  • Comments: 23 (3 by maintainers)

Commits related to this issue

Most upvoted comments

+1 Ihave the same issue on RN 0.57 (debug mode)

I see the same issue as well, and as @markusekblad mentioned, it seems to only appear in release builds. I suspect this is just a timing issue since release builds likely load all the RN javascript much earlier/faster than debug builds.

I’m seeing cases where the app state never transitions to active and stays at unknown. Any ideas?

It seems only happening on >= iOS11 and in release mode.

I am seeing this as well with React Native 0.59.4, on iOS 11.4.1

I’m still seeing this as well on 0.57

I also see this issue in RN 55.3. I get appState ‘unknown’ when it should be ‘active’.