mirror of https://git.lenooby09.tech/LeNooby09/social-app.git
at session-2.1 56 lines 2.1 kB view raw
1import * as Updates from 'expo-updates' 2import {useCallback, useEffect} from 'react' 3import {AppState} from 'react-native' 4import {logger} from '#/logger' 5 6export function useOTAUpdate() { 7 // HELPER FUNCTIONS 8 const checkForUpdate = useCallback(async () => { 9 logger.debug('useOTAUpdate: Checking for update...') 10 try { 11 // Check if new OTA update is available 12 const update = await Updates.checkForUpdateAsync() 13 // If updates aren't available stop the function execution 14 if (!update.isAvailable) { 15 return 16 } 17 // Otherwise fetch the update in the background, so even if the user rejects switching to latest version it will be done automatically on next relaunch. 18 await Updates.fetchUpdateAsync() 19 } catch (e) { 20 logger.error('useOTAUpdate: Error while checking for update', { 21 message: e, 22 }) 23 } 24 }, []) 25 const updateEventListener = useCallback((event: Updates.UpdateEvent) => { 26 logger.debug('useOTAUpdate: Listening for update...') 27 if (event.type === Updates.UpdateEventType.ERROR) { 28 logger.error('useOTAUpdate: Error while listening for update', { 29 message: event.message, 30 }) 31 } else if (event.type === Updates.UpdateEventType.NO_UPDATE_AVAILABLE) { 32 // Handle no update available 33 // do nothing 34 } else if (event.type === Updates.UpdateEventType.UPDATE_AVAILABLE) { 35 // Handle update available 36 // open modal, ask for user confirmation, and reload the app 37 } 38 }, []) 39 40 useEffect(() => { 41 // ADD EVENT LISTENERS 42 const updateEventSubscription = Updates.addListener(updateEventListener) 43 const appStateSubscription = AppState.addEventListener('change', state => { 44 if (state === 'active' && !__DEV__) { 45 checkForUpdate() 46 } 47 }) 48 49 // REMOVE EVENT LISTENERS (CLEANUP) 50 return () => { 51 updateEventSubscription.remove() 52 appStateSubscription.remove() 53 } 54 }, []) // eslint-disable-line react-hooks/exhaustive-deps 55 // disable exhaustive deps because we don't want to run this effect again 56}