React-native-navigation: componentDidAppear does not fire when app brought from background to foreground

Created on 27 Aug 2019  路  2Comments  路  Source: wix/react-native-navigation

Issue Description

I am using componentDidAppear to run some logic when the component comes into view. It works fine when navigating from one screen to the other. But it does not work when bringing the app from background to foreground.

Is there a workaround for this?

Steps to Reproduce

Navigate to this component from another screen: logs 'component did appear'
Put app in background, then in foreground again: no log.

class SomeScreen extends React.Component {

componentDidMount() {
    this.navigationEventListener = Navigation.events().bindComponent(this)
  }

componentDidAppear() {
    console.log('component did appear')

    // do stuff
  }

// render stuff

}

Environment

  • React Native Navigation: 2.18.5-snapshot.330
  • React Native version: 0.59.9
  • Platform(s) (iOS, Android, or both?): Both
  • Device info: Simulators in debug mode: iPhone 6 (12.4), Android Nexus 5X API 23

Most helpful comment

Nevermind, this behavior is built into React Native with the AppState API
https://facebook.github.io/react-native/docs/appstate

So as per the docs we can do:

import React, {Component} from 'react';
import {AppState, Text} from 'react-native';

class AppStateExample extends Component {
  state = {
    appState: AppState.currentState,
  };

  componentDidMount() {
    AppState.addEventListener('change', this._handleAppStateChange);
  }

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

  _handleAppStateChange = (nextAppState) => {
    if (
      this.state.appState.match(/inactive|background/) &&
      nextAppState === 'active'
    ) {
      console.log('App has come to the foreground!');
    }
    this.setState({appState: nextAppState});
  };

  render() {
    return <Text>Current state is: {this.state.appState}</Text>;
  }
}

All 2 comments

Nevermind, this behavior is built into React Native with the AppState API
https://facebook.github.io/react-native/docs/appstate

So as per the docs we can do:

import React, {Component} from 'react';
import {AppState, Text} from 'react-native';

class AppStateExample extends Component {
  state = {
    appState: AppState.currentState,
  };

  componentDidMount() {
    AppState.addEventListener('change', this._handleAppStateChange);
  }

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

  _handleAppStateChange = (nextAppState) => {
    if (
      this.state.appState.match(/inactive|background/) &&
      nextAppState === 'active'
    ) {
      console.log('App has come to the foreground!');
    }
    this.setState({appState: nextAppState});
  };

  render() {
    return <Text>Current state is: {this.state.appState}</Text>;
  }
}

@LaVielle Thanks for sharing!

Was this page helpful?
0 / 5 - 0 ratings