UNPKG

2.14 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.useOnMount = useOnMount;
7exports.useOnEvent = useOnEvent;
8exports.deviceInfoEmitter = void 0;
9
10var _react = require("react");
11
12var _reactNative = require("react-native");
13
14/**
15 * simple hook wrapper for async functions for 'on-mount / componentDidMount' that only need to fired once
16 * @param asyncGetter async function that 'gets' something
17 * @param initialResult -1 | false | 'unknown'
18 */
19function useOnMount(asyncGetter, initialResult) {
20 const [response, setResponse] = (0, _react.useState)({
21 loading: true,
22 result: initialResult
23 });
24 (0, _react.useEffect)(() => {
25 // async function cuz react complains if useEffect's effect param is an async function
26 const getAsync = async () => {
27 const result = await asyncGetter();
28 setResponse({
29 loading: false,
30 result
31 });
32 };
33
34 getAsync();
35 }, [asyncGetter]);
36 return response;
37}
38
39const deviceInfoEmitter = new _reactNative.NativeEventEmitter(_reactNative.NativeModules.RNDeviceInfo);
40/**
41 * simple hook wrapper for handling events
42 * @param eventName
43 * @param initialValueAsyncGetter
44 * @param defaultValue
45 */
46
47exports.deviceInfoEmitter = deviceInfoEmitter;
48
49function useOnEvent(eventName, initialValueAsyncGetter, defaultValue) {
50 const {
51 loading,
52 result: initialResult
53 } = useOnMount(initialValueAsyncGetter, defaultValue);
54 const [result, setResult] = (0, _react.useState)(defaultValue); // sets the result to what the intial value is on mount
55
56 (0, _react.useEffect)(() => {
57 setResult(initialResult);
58 }, [initialResult]); // - set up the event listener to set the result
59 // - set up the clean up function to remove subscription on unmount
60
61 (0, _react.useEffect)(() => {
62 const subscription = deviceInfoEmitter.addListener(eventName, setResult);
63 return () => subscription.remove();
64 }, [eventName]); // loading will only be true while getting the inital value. After that, it will always be false, but a new result may occur
65
66 return {
67 loading,
68 result
69 };
70}
71//# sourceMappingURL=asyncHookWrappers.js.map
\No newline at end of file