expo-duooomi-app/hooks/use-update-checker.ts

89 lines
2.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import * as Sentry from '@sentry/react-native'
import * as Updates from 'expo-updates'
import { useEffect, useState } from 'react'
interface UseUpdateCheckerOptions {
/** 检查更新的间隔时间毫秒默认1分钟 */
interval?: number
/** 是否启用定时检查默认true */
enablePeriodicCheck?: boolean
}
export const useUpdateChecker = ({
interval = 1 * 60 * 1000, // 5分钟
// 关闭轮询
enablePeriodicCheck = false,
}: UseUpdateCheckerOptions = {}) => {
const [hasUpdate, setHasUpdate] = useState(false)
const [isChecking, setIsChecking] = useState(false)
const [checkError, setCheckError] = useState<string | null>(null)
const checkForUpdates = async () => {
// 只在非开发环境下检查更新
if (__DEV__ || !Updates.isEnabled) {
return false
}
try {
setIsChecking(true)
setCheckError(null)
// 检查是否有更新可用
const update = await Updates.checkForUpdateAsync()
console.log('update-------', update)
Sentry.captureMessage('useUpdateChecker', {
tags: {
useUpdateChecker: 'checkForUpdateAsync',
component: 'useUpdateChecker',
},
contexts: {
update: update,
},
})
if (update.isAvailable) {
setHasUpdate(true)
return true
} else {
setHasUpdate(false)
return false
}
} catch (error) {
console.error('检查更新失败:', error)
setCheckError(error instanceof Error ? error.message : '检查更新失败')
setHasUpdate(false)
Sentry.captureMessage('useUpdateCheckerError', {
tags: {
useUpdateChecker: 'checkForUpdateAsync_failed',
component: 'useUpdateChecker',
},
contexts: {
update: {
isEnabled: Updates.isEnabled,
__DEV__: __DEV__,
},
},
})
return false
} finally {
setIsChecking(false)
}
}
useEffect(() => {
checkForUpdates()
}, [])
// 使用 useInterval 进行定时检查
const updateTimer = setInterval(checkForUpdates, enablePeriodicCheck ? interval : undefined)
return {
hasUpdate,
isChecking,
checkError,
checkForUpdates,
}
}