@silicon.js/app-updates
Version:
lightweight react package for checking app updates from ios app store and android play store using react context
85 lines (75 loc) • 2.12 kB
text/typescript
import { useState, useEffect, useCallback } from 'react';
import { AppUpdatesContextType, AppUpdatesInfo } from '../provider/AppUpdatesContext';
import { fetchAppUpdates } from '../fetch';
import { utils } from '../utils';
export interface UseAppUpdatesProps {
currentVersion: string;
appId: string; // Bundle ID for iOS or package name for Android
platform: 'ios' | 'android';
autoCheck?: boolean; // automatically check on mount
countryCode?: string; // for iOS App Store (default: 'us')
}
export const useAppUpdates = ({
currentVersion,
appId,
platform,
autoCheck = true,
countryCode = 'us',
}: UseAppUpdatesProps): AppUpdatesContextType => {
const [details, setDetails] = useState<AppUpdatesInfo>({
currentVersion,
latestVersion: null,
isNewVersionAvailable: false,
isChecking: false,
lastChecked: null,
error: null,
});
const checkVersion = useCallback(async () => {
setDetails((prev) => {
if (prev.isChecking) return prev;
return { ...prev, isChecking: true, error: null };
});
try {
let latestVersion: string | null = null;
if (platform === 'ios') {
latestVersion = await fetchAppUpdates.ios(appId, countryCode);
} else if (platform === 'android') {
latestVersion = await fetchAppUpdates.android(appId);
}
if (latestVersion) {
const isNewVersionAvailable = utils.compareVersions(currentVersion, latestVersion);
setDetails({
currentVersion,
latestVersion,
isNewVersionAvailable,
isChecking: false,
lastChecked: new Date(),
error: null,
});
} else {
setDetails((prev) => ({
...prev,
isChecking: false,
lastChecked: new Date(),
error: 'Unable to fetch latest version',
}));
}
} catch (error) {
setDetails((prev) => ({
...prev,
isChecking: false,
lastChecked: new Date(),
error: error instanceof Error ? error.message : 'Unknown error occurred',
}));
}
}, [currentVersion, appId, platform, countryCode]);
useEffect(() => {
if (autoCheck) {
checkVersion();
}
}, [autoCheck, checkVersion]);
return {
details,
checkVersion,
};
};