Search code examples
androidreact-nativereact-native-push-notification

React Native: AppState.addEventListener registering duplicate events on resume when tapping a notification


I have code which I want to run when my app resumes from the background. To this end, I register an event using AppState.addEventListener().

  const handleAppStateChange = () => {
    console.log('Do stuff')
  }

  constructor(props: Props) {
    super(props)
    AppState.addEventListener('change', this.handleAppStateChange)
  }

  componentWillUnmount() {
    AppState.removeEventListener('change', this.handleAppStateChange)
  }

When I normally exit the app and resume, it prints 'do stuff' as expected, however (and here is the issue), when the app is minimised and I tap on a notification, the app will print 'Do stuff' twice.

I have figured out it's because when I tap a notification, it seems to re-run the app (including the constructor part), which means it creates a second event listener...

So, does anyone know either why it's doing that when tapping on a notification and if I can prevent it (using react-native-push-notification plugin), or alternatively if there is a way I can ensure that duplicate events are not registered?

This is happening on my Android physical device, not sure if it's an iOS issue as well, but just thought I would check if anyone knew if this was possible)


Solution

  • So after much agonising, I have managed to come up with a solution. It's not great, but gets the job done for now.

    if (AppState._eventHandlers.change.size === 0) {
      AppState.addEventListener('change', this.handleAppStateChange)
    }
    

    I feel the AppState page https://facebook.github.io/react-native/docs/appstate, is woefully inadequate, and that is why the only option I could see right now is this private method. Will try and follow up with the team if this could be improved, because it would make sense that in some cases you don't want duplicated events to be registered.