Skip to content

Commit d2afe76

Browse files
fix(useBattery): handle unmount cleanup and promise rejection
- Add mounted flag to prevent state updates after unmount - Prevent event listener registration if component unmounts before getBattery() resolves - Add .catch() handler to gracefully handle promise rejections - Fix misleading comment for fetched field
1 parent 243087f commit d2afe76

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

src/useBattery/index.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ export type UseBatteryState = BatteryState & {
2727
*/
2828
isSupported: boolean;
2929
/**
30-
* Whether the battery state is currently being fetched.
30+
* Whether the battery state has been fetched.
3131
*/
3232
fetched: boolean;
3333
};
@@ -96,15 +96,20 @@ export function useBattery(): UseBatteryState {
9696
}
9797

9898
let battery: BatteryManager | null = null;
99+
let mounted = true;
99100

100101
const handleChange = () => {
101-
if (battery) {
102+
if (battery && mounted) {
102103
setState(getBatteryState(battery));
103104
}
104105
};
105106

106107
// eslint-disable-next-line @typescript-eslint/no-floating-promises,promise/catch-or-return,promise/prefer-await-to-then,promise/always-return
107108
nav.getBattery().then((b) => {
109+
if (!mounted) {
110+
return;
111+
}
112+
108113
battery = b;
109114
setState(getBatteryState(battery));
110115

@@ -115,6 +120,7 @@ export function useBattery(): UseBatteryState {
115120
});
116121

117122
return () => {
123+
mounted = false;
118124
if (battery) {
119125
off(battery, 'chargingchange', handleChange);
120126
off(battery, 'chargingtimechange', handleChange);

0 commit comments

Comments
 (0)