Skip to content

Instantly share code, notes, and snippets.

@Pinwheeler
Created August 8, 2021 17:40
Show Gist options
  • Save Pinwheeler/e6ca290fc1eefee3c8f943fa1e6d7fb2 to your computer and use it in GitHub Desktop.
Save Pinwheeler/e6ca290fc1eefee3c8f943fa1e6d7fb2 to your computer and use it in GitHub Desktop.
CodePush FC
import moment from "moment"
import React, { useEffect, useState } from "react"
import { AppState } from "react-native"
import CodePush from "react-native-code-push"
import ContextStack from "src/app/ContextStack"
import { ErrorBoundary } from "src/app/ErrorBoundary"
import RootNavigator from "src/app/RootNavigator"
import { LoadingScreen } from "src/shared/LoadingScreen"
const MIN_BACKGROUND_DURATION_IN_MIN = 30
const App: React.FC = () => {
const [lastBackgroundedTime, setLastBackgroundedTime] = useState<moment.Moment>(moment(0))
const [appState, setAppState] = useState(AppState.currentState)
const [loading, setLoading] = useState(false)
useEffect(() => {
AppState.addEventListener("change", handleAppStateChange)
return () => {
AppState.removeEventListener("change", handleAppStateChange)
}
})
const handleAppStateChange = async (nextAppState) => {
// Try to run the CodePush sync whenever app comes to foreground
if (appState.match(/inactive|background/) && nextAppState === "active") {
// Only run the sync if app has been in the background for a certain amount of time
if (moment.duration(moment().diff(lastBackgroundedTime)).asMinutes() > MIN_BACKGROUND_DURATION_IN_MIN) {
// Please show the user some feedback while running this
// This might take some time, especially if an update is available
setLoading(true)
await CodePush.sync({
installMode: CodePush.InstallMode.IMMEDIATE,
})
setLoading(false)
}
}
if (nextAppState.match(/inactive|background/)) {
setLastBackgroundedTime(moment())
}
if (appState !== nextAppState) {
setAppState(nextAppState)
}
}
return (
<LoadingScreen loading={loading}>
// App rendering code
</LoadingScreen>
)
}
const codePushOptions = { checkFrequency: CodePush.CheckFrequency.MANUAL }
export default CodePush(codePushOptions)(App)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment