import { useState, useEffect } from 'react'; import { DeviceInfoModule } from 'react-native-nitro-device-info'; /** * Monitor battery level changes by polling every five seconds. * * Returns the current battery level as a number between 0.0 and 1.0. * The value updates automatically when the battery level changes. * * @returns Battery level (0.0 to 1.0), or null during initial load or when unavailable * * @example * ```tsx * import { useBatteryLevel } from 'react-native-nitro-device-info'; * * function BatteryIndicator() { * const batteryLevel = useBatteryLevel(); * * if (batteryLevel === null) { * return Loading...; * } * * return Battery: {Math.round(batteryLevel * 100)}%; * } * ``` * * @platform iOS, Android */ export function useBatteryLevel(): number | null { const [batteryLevel, setBatteryLevel] = useState(null); useEffect(() => { const updateBatteryLevel = () => { const currentLevel = DeviceInfoModule.getBatteryLevel(); const nextLevel = currentLevel >= 0 && currentLevel <= 1 ? currentLevel : null; setBatteryLevel(prev => prev === nextLevel ? prev : nextLevel); }; updateBatteryLevel(); const intervalId = setInterval(updateBatteryLevel, 5000); return () => { clearInterval(intervalId); }; }, []); return batteryLevel; }