diff --git a/docs/appstate.md b/docs/appstate.md index 18071592bb2..1ce28c4b84b 100644 --- a/docs/appstate.md +++ b/docs/appstate.md @@ -22,39 +22,108 @@ For more information, see [Apple's documentation](https://developer.apple.com/do To see the current state, you can check `AppState.currentState`, which will be kept up-to-date. However, `currentState` will be null at launch while `AppState` retrieves it over the bridge. -```jsx -import React, {Component} from 'react'; -import {AppState, Text} from 'react-native'; +
+ +
+ + + +```SnackPlayer name=AppState%20Function%20Component%20Example +import React, { useEffect, useState } from "react"; +import { AppState, StyleSheet, Text, View } from "react-native"; + +const AppStateExample = () => { + const [appState, setAppState] = useState(AppState.currentState); + + useEffect(() => { + AppState.addEventListener("change", _handleAppStateChange); + + return () => { + AppState.removeEventListener("change", _handleAppStateChange); + }; + }, []); + + const _handleAppStateChange = nextAppState => { + if (appState.match(/inactive|background/) && nextAppState === "active") { + console.log("App has come to the foreground!"); + } + setAppState(nextAppState); + }; + + return ( + + Current state is: {appState} + + ); +}; + +const styles = StyleSheet.create({ + container: { + flex: 1, + justifyContent: "center", + alignItems: "center" + } +}); + +export default AppStateExample; +``` + + + +```SnackPlayer name=AppState%20Class%20Component%20Example +import React, { Component } from "react"; +import { AppState, StyleSheet, Text, View } from "react-native"; -class AppStateExample extends Component { +export default class AppStateExample extends Component { state = { - appState: AppState.currentState, + appState: AppState.currentState }; componentDidMount() { - AppState.addEventListener('change', this._handleAppStateChange); + AppState.addEventListener("change", this._handleAppStateChange); } componentWillUnmount() { - AppState.removeEventListener('change', this._handleAppStateChange); + AppState.removeEventListener("change", this._handleAppStateChange); } - _handleAppStateChange = (nextAppState) => { + _handleAppStateChange = nextAppState => { if ( this.state.appState.match(/inactive|background/) && - nextAppState === 'active' + nextAppState === "active" ) { - console.log('App has come to the foreground!'); + console.log("App has come to the foreground!"); } - this.setState({appState: nextAppState}); + this.setState({ appState: nextAppState }); }; render() { - return Current state is: {this.state.appState}; + return ( + + Current state is: {this.state.appState} + + ); } } + +const styles = StyleSheet.create({ + container: { + flex: 1, + justifyContent: "center", + alignItems: "center" + } +}); ``` + + This example will only ever appear to say "Current state is: active" because the app is only visible to the user when in the `active` state, and the null state will happen only momentarily. ---