forked from CSFrequency/react-firebase-hooks
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseObject.ts
More file actions
58 lines (51 loc) · 1.62 KB
/
useObject.ts
File metadata and controls
58 lines (51 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import { useEffect, useMemo } from 'react';
import { snapshotToData, ValOptions } from './helpers';
import { ObjectHook, ObjectValHook, Val } from './types';
import { useIsEqualRef, useLoadingValue } from '../util';
import { DataSnapshot, off, onValue, Query } from 'firebase/database';
export const useObject = (query?: Query | null): ObjectHook => {
const { error, loading, reset, setError, setValue, value } = useLoadingValue<
DataSnapshot,
Error
>();
const ref = useIsEqualRef(query, reset);
useEffect(() => {
const query = ref.current;
if (!query) {
setValue(undefined);
return;
}
onValue(query, setValue, setError);
return () => {
off(query, 'value', setValue);
};
}, [ref.current]);
const resArray: ObjectHook = [value, loading, error];
return useMemo(() => resArray, resArray);
};
export const useObjectVal = <
T,
KeyField extends string = '',
RefField extends string = ''
>(
query?: Query | null,
options?: ValOptions<T>
): ObjectValHook<T, KeyField, RefField> => {
const keyField = options ? options.keyField : undefined;
const refField = options ? options.refField : undefined;
const transform = options ? options.transform : undefined;
const [snapshot, loading, error] = useObject(query);
const value = useMemo(
() =>
(snapshot
? snapshotToData(snapshot, keyField, refField, transform)
: undefined) as Val<T, KeyField, RefField>,
[snapshot, keyField, refField, transform]
);
const resArray: ObjectValHook<T, KeyField, RefField> = [
value,
loading,
error,
];
return useMemo(() => resArray, resArray);
};