useBattery
A custom hook for fetching battery status information.
Add hook
Create a file use-battery.ts
and copy & paste the code from useBattery.
Hook
import { useEffect, useState } from 'react'
interface BatteryManager {
charging: boolean
chargingTime: number
dischargingTime: number
level: number
}
export const useBattery = (): BatteryManager | undefined => {
const [battery, setBattery] = useState<BatteryManager>()
const updateBatteryStatus = async () => {
try {
/* eslint-disable @typescript-eslint/no-explicit-any */
const batteryInfo: BatteryManager = await (navigator as any).getBattery()
if (batteryInfo) {
setBattery(batteryInfo)
}
} catch (error) {
console.error('Error getting battery status:', error)
}
}
useEffect(() => {
updateBatteryStatus()
const intervalId = setInterval(updateBatteryStatus, 30000)
return () => clearInterval(intervalId)
}, [])
return battery
}
Usage
import React, { useEffect, useState } from 'react';
import { useBattery } from './hooks/use-battery';
function App() {
const battery = useBattery();
if (!battery) {
return <div>Battery status unavailable</div>;
}
return (
<div>
<h1>Battery Status</h1>
<p>Charging: {battery.charging ? 'Yes' : 'No'}</p>
<p>Charging Time: {battery.chargingTime}</p>
<p>Discharging Time: {battery.dischargingTime}</p>
<p>Level: {battery.level}</p>
</div>
);
}
export default App;
API
Returns
Name | Type | Description |
---|---|---|
charging | boolean | Indicates whether the battery is currently charging. |
chargingTime | number | The estimated time, in seconds, until the battery is fully charged. |
dischargingTime | number | The estimated time, in seconds, until the battery is fully discharged. |
level | number | The battery level, expressed as a percentage (0 to 1). |