source: imaps-frontend/node_modules/react-use/lib/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: 2.1 KB
Line 
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3var tslib_1 = require("tslib");
4var react_1 = require("react");
5var util_1 = require("./misc/util");
6var isDeepEqual_1 = tslib_1.__importDefault(require("./misc/isDeepEqual"));
7var nav = util_1.isNavigator ? navigator : undefined;
8var isBatteryApiSupported = nav && typeof nav.getBattery === 'function';
9function useBatteryMock() {
10 return { isSupported: false };
11}
12function useBattery() {
13 var _a = react_1.useState({ isSupported: true, fetched: false }), state = _a[0], setState = _a[1];
14 react_1.useEffect(function () {
15 var isMounted = true;
16 var battery = null;
17 var handleChange = function () {
18 if (!isMounted || !battery) {
19 return;
20 }
21 var newState = {
22 isSupported: true,
23 fetched: true,
24 level: battery.level,
25 charging: battery.charging,
26 dischargingTime: battery.dischargingTime,
27 chargingTime: battery.chargingTime,
28 };
29 !isDeepEqual_1.default(state, newState) && setState(newState);
30 };
31 nav.getBattery().then(function (bat) {
32 if (!isMounted) {
33 return;
34 }
35 battery = bat;
36 util_1.on(battery, 'chargingchange', handleChange);
37 util_1.on(battery, 'chargingtimechange', handleChange);
38 util_1.on(battery, 'dischargingtimechange', handleChange);
39 util_1.on(battery, 'levelchange', handleChange);
40 handleChange();
41 });
42 return function () {
43 isMounted = false;
44 if (battery) {
45 util_1.off(battery, 'chargingchange', handleChange);
46 util_1.off(battery, 'chargingtimechange', handleChange);
47 util_1.off(battery, 'dischargingtimechange', handleChange);
48 util_1.off(battery, 'levelchange', handleChange);
49 }
50 };
51 }, []);
52 return state;
53}
54exports.default = isBatteryApiSupported ? useBattery : useBatteryMock;
Note: See TracBrowser for help on using the repository browser.