tscizzle
tscizzle

Reputation: 12241

React Native - render when app comes into foreground

I have a simple display which is based on some async data.

My code is as such:

componentDidMount() {
  asynFunctionCall(result => {
    this.setState({stateVariable: result});
  });
}

And I use the state variable stateVariable to decide whether or not to show a <Text> component:

render() {
  return (
    <View>
      {this.state.stateVariable &&
        <Text> Special Message </Text>
      }
    </View>
  );
}

What I want is for asyncFunctionCall to be run whenever the app comes to the foreground so that the user can leave the app, do something (which may affect the result of that async call), and come back to the app and have the display updated appropriately.

This seems like a standard app behavior, and I wonder if React Native's lifecycle API has a standard way to support it, but I'm not finding it.

How can I achieve this behavior, with a lifecycle function or otherwise?

Upvotes: 1

Views: 6709

Answers (2)

evanjmg
evanjmg

Reputation: 3795

AppState should work mostly for iOS, but for Android background activity is triggered anytime a native module outside of your own code is triggered, e.g capturing a photo. It is way better to detect home or recent app button clicks. This is because fragments within your app from other apps like social media or photos will also trigger background state, which you don't want because they are still in the app adding a photo to a profile from the camera etc. You can easily detect home and recent app button clicks on Android with react-native-home-pressed. This library simply exposes the android button events.

First install the library with npm i react-native-home-pressed --save and then link it react-native link. Then rebuild your app and add the following snippet.

import { DeviceEventEmitter } from 'react-native'

class ExampleComponent extends Component {
  componentDidMount() {
    this.onHomeButtonPressSub = DeviceEventEmitter.addListener(
     'ON_HOME_BUTTON_PRESSED',
     () => {
       console.log('You tapped the home button!')
    })
    this.onRecentButtonPressSub = DeviceEventEmitter.addListener(
     'ON_RECENT_APP_BUTTON_PRESSED',
     () => {
       console.log('You tapped the recent app button!')
    })
  }
   componentWillUnmount(): void {
    if (this.onRecentButtonPressSub)   this.onRecentButtonPressSub.remove()
    if (this.onHomeButtonPressSub) this.onHomeButtonPressSub.remove()
  }
}

Upvotes: 0

agenthunt
agenthunt

Reputation: 8678

Yes. you can use the AppState https://facebook.github.io/react-native/docs/appstate.html API.

I would suggest to add this somewhere at the start of the app and coordinate your views accordingly.

Upvotes: 3

Related Questions