Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed the Function Component Example #2019

Merged
merged 4 commits into from
Jul 6, 2020
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 24 additions & 16 deletions docs/appstate.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,30 +36,38 @@ To see the current state, you can check `AppState.currentState`, which will be k
<block class="functional syntax" />

```SnackPlayer name=AppState%20Function%20Component%20Example
import React, { useEffect, useRef } from "react";
import React, { useRef, useState, useEffect } from "react";
import { AppState, StyleSheet, Text, View } from "react-native";

const AppStateExample = () => {
const appState = useRef(AppState.currentState);

useEffect(() => {
AppState.addEventListener("change", _handleAppStateChange);

return () => {
AppState.removeEventListener("change", _handleAppStateChange);
/*
You can remove line 7 & 24 if you don't want to see the AppState update from active to inactive (iOS)
You then must alter line 30 to something like appState.current
*/
const [appStateVisible, setAppStateVisible] = useState(appState.current);

useEffect(() => {
AppState.addEventListener('change', _handleAppStateChange);

return () => {
AppState.removeEventListener('change', _handleAppStateChange);
};
}, []);

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

appState.current = nextAppState;
console.log("AppState", appState.current);
setAppStateVisible(appState.current);
};
}, [_handleAppStateChange]);

const _handleAppStateChange = (nextAppState) => {
if (appState.current.match(/inactive|background/) && nextAppState === "active") {
console.log("App has come to the foreground!");
}
appState.current = nextAppState;
};

return (
<View style={styles.container}>
<Text>Current state is: {appState.current}</Text>
<Text>Current state is: {appStateVisible}</Text>
</View>
);
};
Expand Down