How can I set some functions to run while the AppState is inactive in react-native

Viewed 448

I try to add a number to a variable in the databas when the AppState is inactive and I do not know what to do

AppState.addEventListener('change', () => this.handleAppStateChange())
handleAppStateChange(){
    if(AppState.currentState === 'inactive'){
        addIncome().then().catch(error => {})
    }
}
1 Answers

You should add and remove AppState change listener in componentDidMount and componentWillUnmount:

state = {lastAppState: AppState.currentState};

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

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

And also you need to save the latest AppState in state and check it when AppState changes, to find out when it changes to inactive:

handleAppStateChange = (nextAppState) => {
  if (
    this.state.lastAppState === 'active' &&
    nextAppState.match(/inactive|background/)
  ) {
    // your app state changes to inactive
  }

  this.setState({lastAppState: nextAppState});
};
Related