source: imaps-frontend/node_modules/react-use/esm/useBattery.js

main
Last change on this file was d565449, checked in by stefan toskovski <stefantoska84@…>, 4 weeks ago

Update repo after prototype presentation

  • Property mode set to 100644
File size: 1.9 KB
Line 
1import { useEffect, useState } from 'react';
2import { isNavigator, off, on } from './misc/util';
3import isDeepEqual from './misc/isDeepEqual';
4var nav = isNavigator ? navigator : undefined;
5var isBatteryApiSupported = nav && typeof nav.getBattery === 'function';
6function useBatteryMock() {
7 return { isSupported: false };
8}
9function useBattery() {
10 var _a = useState({ isSupported: true, fetched: false }), state = _a[0], setState = _a[1];
11 useEffect(function () {
12 var isMounted = true;
13 var battery = null;
14 var handleChange = function () {
15 if (!isMounted || !battery) {
16 return;
17 }
18 var newState = {
19 isSupported: true,
20 fetched: true,
21 level: battery.level,
22 charging: battery.charging,
23 dischargingTime: battery.dischargingTime,
24 chargingTime: battery.chargingTime,
25 };
26 !isDeepEqual(state, newState) && setState(newState);
27 };
28 nav.getBattery().then(function (bat) {
29 if (!isMounted) {
30 return;
31 }
32 battery = bat;
33 on(battery, 'chargingchange', handleChange);
34 on(battery, 'chargingtimechange', handleChange);
35 on(battery, 'dischargingtimechange', handleChange);
36 on(battery, 'levelchange', handleChange);
37 handleChange();
38 });
39 return function () {
40 isMounted = false;
41 if (battery) {
42 off(battery, 'chargingchange', handleChange);
43 off(battery, 'chargingtimechange', handleChange);
44 off(battery, 'dischargingtimechange', handleChange);
45 off(battery, 'levelchange', handleChange);
46 }
47 };
48 }, []);
49 return state;
50}
51export default isBatteryApiSupported ? useBattery : useBatteryMock;
Note: See TracBrowser for help on using the repository browser.