UNPKG

1.98 kBPlain TextView Raw
1import { useState, useEffect } from 'react';
2import { NativeEventEmitter, NativeModules } from 'react-native';
3import type { AsyncHookResult } from './types';
4
5/**
6 * simple hook wrapper for async functions for 'on-mount / componentDidMount' that only need to fired once
7 * @param asyncGetter async function that 'gets' something
8 * @param initialResult -1 | false | 'unknown'
9 */
10export function useOnMount<T>(asyncGetter: () => Promise<T>, initialResult: T): AsyncHookResult<T> {
11 const [response, setResponse] = useState<AsyncHookResult<T>>({
12 loading: true,
13 result: initialResult,
14 });
15
16 useEffect(() => {
17 // async function cuz react complains if useEffect's effect param is an async function
18 const getAsync = async () => {
19 const result = await asyncGetter();
20 setResponse({ loading: false, result });
21 };
22
23 getAsync();
24 }, [asyncGetter]);
25
26 return response;
27}
28
29export const deviceInfoEmitter = new NativeEventEmitter(NativeModules.RNDeviceInfo);
30
31/**
32 * simple hook wrapper for handling events
33 * @param eventName
34 * @param initialValueAsyncGetter
35 * @param defaultValue
36 */
37export function useOnEvent<T>(
38 eventName: string,
39 initialValueAsyncGetter: () => Promise<T>,
40 defaultValue: T
41): AsyncHookResult<T> {
42 const { loading, result: initialResult } = useOnMount(initialValueAsyncGetter, defaultValue);
43 const [result, setResult] = useState<T>(defaultValue);
44
45 // sets the result to what the intial value is on mount
46 useEffect(() => {
47 setResult(initialResult);
48 }, [initialResult]);
49
50 // - set up the event listener to set the result
51 // - set up the clean up function to remove subscription on unmount
52 useEffect(() => {
53 const subscription = deviceInfoEmitter.addListener(eventName, setResult);
54 return () => subscription.remove();
55 }, [eventName]);
56
57 // loading will only be true while getting the inital value. After that, it will always be false, but a new result may occur
58 return { loading, result };
59}