React Native Code Push provides a nice way of sending OTA updates and helps release bug fixes without any need to release via Play Store and App Store.
There are two ways you can consume OTAs
- Automatic Check and Install ⇒ Default
- Manual Check and Install
There can be scenarios you might want to opt for Manual instead of Automatic, For example a Financial App where you don’t want the update to be installed unless someone clicks apply. Or you are sending OTAs but QA doesn’t see it. So you can provide UI for them to download latest OTA
Check if there is new OTA update available
In order to check if there is codepush update available you can do it this way
const CodePushComponent = observer(() => {
const codePushModel = useObservable({
status: 'init',
isUpdateAvailable: false,
updateMeta: null,
isDownloading: false,
downloadProgress: 0,
})
const handleCheckForUpdates = async () => {
try {
codepushModel.status.set('pending');
const update = await codePush.checkForUpdate();
codepushModel.status.set('success');
if (update) {
codepushModel.isUpdateAvailable.set(true);
codepushModel.updateMeta.set(update);
}
console.log({update});
} catch (error) {
codepushModel.status.set('error');
console.log({error});
}
};
const handleDownloadAndInstall = async () => {
try {
const update = codepushModel.updateMeta.peek() as unknown as RemotePackage;
if (update.isPending) {
codePush.restartApp();
} else {
codepushModel.isDownloading.set(true);
const download = await update.download((progress: DownloadProgress) => {
const percentageDownloaded = progress.receivedBytes / progress.totalBytes;
codepushModel.downloadProgress.set(percentageDownloaded);
});
await download.install(codePush.InstallMode.IMMEDIATE);
}
} catch (error) {
snackbarNotificationActions.notifySnackbar({message: error?.message});
} finally {
codepushModel.isDownloading.set(false);
}
};
const checkingforUpdate = codepushModel.status.get() === 'pending';
return (
<Show if={ENV.environment === 'development'}>
<View style={styles.container}>
<Button onPress={handleCheckForUpdates} mode={'outlined'} loading={checkingforUpdate}>
<Text>{checkingforUpdate ? 'Checking' : 'Check for updates'}</Text>
</Button>
<Show if={codepushModel.updateMeta}>
<Button onPress={handleDownloadAndInstall}>
<Text>{'Download and Install'}</Text>
</Button>
</Show>
<Show if={codepushModel.isDownloading}>
<Surface>
<ProgressBar progress={codepushModel.downloadProgress.get()} />
</Surface>
</Show>
</View>
</Show>
);
})The async method codePush.checkForUpdate() either returns update data or null
If there is an update, you can use the update result returned for checkForUpdate which contains download method.
The download method contains one callback argument which provides progress of the download.
Once the download is successful, you can call install method that’s attached to download and provide options on when to install it