diff --git a/reason-react-native/src/apis/AppState.md b/reason-react-native/src/apis/AppState.md index d84b79927c5b7a..54cbac63907f8e 100644 --- a/reason-react-native/src/apis/AppState.md +++ b/reason-react-native/src/apis/AppState.md @@ -48,3 +48,46 @@ external removeEventListener: ""; ``` + +# Example + +The example below illustrates rendering to the ui based on the value returned from the `AppState` API. + +```reason +[@react.component] + let make = () => { + let (appState, setAppState) = React.useState(_ => AppState.currentState); + + let handleAppStateChange = nextAppState => { + switch (appState, nextAppState) { + | (_, state) when state === AppState.background => + Js.log("App has come to the background!") + | (_, state) when state === AppState.active => + Js.log("App has come to the foreground!") + | _ => () + }; + setAppState(_ => nextAppState); + }; + + React.useEffect(() => { + AppState.addEventListener( + `change(state => handleAppStateChange(state)), + ) + Some( + () => + AppState.removeEventListener( + `change(state => handleAppStateChange(state)), + ), + ); + }); + + let renderAppState = + switch (appState) { + | appState when appState === AppState.active => "active" + | appState when appState === AppState.background => "background" + | appState when appState === AppState.inactive => "inactive" + | _ => "unknown" + }; + {"Current state is: " ++ renderAppState |> React.string} ; + }; +```