Last active
May 9, 2025 18:42
-
-
Save williamjayjay/44dfc0056737942aad68ba1659c28fbb to your computer and use it in GitHub Desktop.
React Native useCheckAppVersion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useNavigation } from "@react-navigation/native"; | |
import { useEffect, useState } from "react"; | |
import { Modal, View, Text, Button, Platform, Linking, Alert } from "react-native"; | |
import { useTranslation } from "react-i18next"; | |
import VersionCheck from "react-native-version-check"; | |
export function useCheckAppVersion() { | |
const [showModal, setShowModal] = useState(false); | |
const [latestVersion, setLatestVersion] = useState(""); | |
const navigation = useNavigation(); | |
const { t: translate } = useTranslation(); // Hook para acessar traduções | |
useEffect(() => { | |
async function checkVersion() { | |
try { | |
const latestVersion = await VersionCheck.getLatestVersion(); // Obtém a versão mais recente | |
const currentVersion = VersionCheck.getCurrentVersion(); // Obtém a versão instalada | |
// if ( latestVersion > currentVersion ) { | |
if ( latestVersion > currentVersion ) { | |
setLatestVersion(latestVersion); | |
setShowModal(true); | |
Alert.alert( | |
translate("checkVersion.update_available"), | |
translate("checkVersion.new_version_available", { version: latestVersion }), | |
[ | |
{ | |
text: translate("checkVersion.update_now"), | |
onPress: handleUpdate, | |
}, | |
] | |
); | |
} | |
} catch (error) { | |
console.error("Erro ao verificar versão:", error); | |
} | |
} | |
const unsubscribe = navigation.addListener("state", async () => { | |
checkVersion(); | |
}); | |
return unsubscribe; | |
}, [navigation]); | |
async function handleUpdate() { | |
const storeUrl = | |
Platform.OS === "ios" | |
? VersionCheck.getAppStoreUrl() | |
: VersionCheck.getPlayStoreUrl(); | |
Linking.openURL(await storeUrl); | |
} | |
return ( | |
<Modal visible={showModal} transparent animationType="slide"> | |
<View | |
style={{ | |
flex: 1, | |
justifyContent: "center", | |
alignItems: "center", | |
backgroundColor: "rgba(0,0,0,0.5)", | |
zIndex:9999 | |
}} | |
> | |
<View | |
style={{ backgroundColor: "white", padding: 20, borderRadius: 10 }} | |
> | |
<Text allowFontScaling={false} style={{ fontSize: 18, fontWeight: "bold" }}> | |
Atualização disponível! | |
</Text> | |
<Text allowFontScaling={false} style={{ marginVertical: 10 }}> | |
Uma nova versão ({latestVersion}) está disponível. Atualize para | |
continuar usando o app. | |
</Text> | |
<Button title="Atualizar Agora" onPress={handleUpdate} /> | |
</View> | |
</View> | |
</Modal> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment