mirror of
https://github.com/streamich/react-use.git
synced 2025-12-08 18:02:14 +00:00
Added fetching indicator; Fixed isMounted state; Mock function returned for browsers not supporting the Battery API; Using react-fast-compare to avoid useless updates;
2.1 KiB
2.1 KiB
useBattery
React sensor hook that tracks battery status.
Note: current
BatteryManagerAPI state is obsolete.
Although it may still work in some browsers, its use is discouraged since it could be removed at any time.
Usage
import {useBattery} from 'react-use';
const Demo = () => {
const batteryState = useBattery();
if (!batteryState.isSupported) {
return (
<div>
<strong>Battery sensor</strong>: <span>not supported</span>
</div>
);
}
if (!batteryState.fetched) {
return (
<div>
<strong>Battery sensor</strong>: <span>supported</span> <br />
<strong>Battery state</strong>: <span>fetching</span>
</div>
);
}
return (
<div>
<strong>Battery sensor</strong>: <span>supported</span> <br />
<strong>Battery state</strong>: <span>fetched</span> <br />
<strong>Charge level</strong>: <span>{ (batteryState.level * 100).toFixed(0) }%</span> <br />
<strong>Charging</strong>: <span>{ batteryState.charging ? 'yes' : 'no' }</span> <br />
<strong>Charging time</strong>:
<span>{ batteryState.chargingTime ? batteryState.chargingTime : 'finished' }</span> <br />
<strong>Discharging time</strong>: <span>{ batteryState.dischargingTime }</span>
</div>
);
};
Reference
const {isSupported, level, charging, dischargingTime, chargingTime} = useBattery();
isSupported: boolean- whether browser/devise supports BatteryManager;fetched: boolean- whether battery state is fetched;level: number- representing the system's battery charge level scaled to a value between 0.0 and 1.0.charging: boolean- indicating whether or not the battery is currently being charged.dischargingTime: number- remaining time in seconds until the battery is completely discharged and the system will suspend.chargingTime: number- remaining time in seconds until the battery is fully charged, or 0 if the battery is already fully charged.