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?
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
}
2.18.5-snapshot.3300.59.9Nevermind, 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!
Most helpful comment
Nevermind, this behavior is built into React Native with the
AppStateAPIhttps://facebook.github.io/react-native/docs/appstate
So as per the docs we can do: