1import { useEffect, useState } from 'react'; 2import { getNativeStateMachineContextAsync } from './Updates'; 3import { addUpdatesStateChangeListener } from './UpdatesEmitter'; 4import { currentlyRunning, defaultUseUpdatesState, reduceUpdatesStateFromContext, } from './UseUpdatesUtils'; 5/** 6 * Hook that obtains information on available updates and on the currently running update. 7 * 8 * @return the structures with information on currently running and available updates. 9 * 10 * @example 11 * ```tsx UpdatesDemo.tsx 12 * import { StatusBar } from 'expo-status-bar'; 13 * import * as Updates from 'expo-updates'; 14 * import React from 'react'; 15 * import { Pressable, Text, View } from 'react-native'; 16 * 17 * export default function UpdatesDemo() { 18 * const { 19 * currentlyRunning, 20 * availableUpdate, 21 * isUpdateAvailable, 22 * isUpdatePending 23 * } = Updates.useUpdates(); 24 * 25 * React.useEffect(() => { 26 * if (isUpdatePending) { 27 * // Update has successfully downloaded 28 * runUpdate(); 29 * } 30 * }, [isUpdatePending]); 31 * 32 * // If true, we show the button to download and run the update 33 * const showDownloadButton = isUpdateAvailable; 34 * 35 * // Show whether or not we are running embedded code or an update 36 * const runTypeMessage = currentlyRunning.isEmbeddedLaunch 37 * ? 'This app is running from built-in code' 38 * : 'This app is running an update'; 39 * 40 * return ( 41 * <View style={styles.container}> 42 * <Text style={styles.headerText}>Updates Demo</Text> 43 * <Text>{runTypeMessage}</Text> 44 * <Button pressHandler={() => Updates.checkForUpdateAsync()} text="Check manually for updates" /> 45 * {showDownloadButton ? ( 46 * <Button pressHandler={() => Updates.fetchUpdateAsync()} text="Download and run update" /> 47 * ) : null} 48 * <StatusBar style="auto" /> 49 * </View> 50 * ); 51 * } 52 * ``` 53 */ 54export const useUpdates = () => { 55 const [updatesState, setUpdatesState] = useState(defaultUseUpdatesState); 56 // Change the state based on native state machine context changes 57 useEffect(() => { 58 getNativeStateMachineContextAsync() 59 .then((context) => { 60 setUpdatesState((updatesState) => reduceUpdatesStateFromContext(updatesState, context)); 61 }) 62 .catch((error) => { 63 // Native call can fail (e.g. if in development mode), so catch the promise rejection and surface the error 64 setUpdatesState((updatesState) => ({ ...updatesState, initializationError: error })); 65 }); 66 const subscription = addUpdatesStateChangeListener((event) => { 67 setUpdatesState((updatesState) => reduceUpdatesStateFromContext(updatesState, event.context)); 68 }); 69 return () => subscription.remove(); 70 }, []); 71 // Return the updates info and the user facing functions 72 return { 73 currentlyRunning, 74 ...updatesState, 75 }; 76}; 77//# sourceMappingURL=UseUpdates.js.map