forked from CSFrequency/react-firebase-hooks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseCollectionOnce.ts
55 lines (50 loc) · 1.44 KB
/
useCollectionOnce.ts
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
import { firestore } from 'firebase';
import { useEffect } from 'react';
import { snapshotToData } from './helpers';
import { LoadingHook, useIsEqualRef, useLoadingValue } from '../util';
export type CollectionOnceHook = LoadingHook<firestore.QuerySnapshot, Error>;
export type CollectionDataOnceHook<T> = LoadingHook<T[], Error>;
export const useCollectionOnce = (
query?: firestore.Query | null,
options?: {
getOptions?: firestore.GetOptions;
}
): CollectionOnceHook => {
const { error, loading, reset, setError, setValue, value } = useLoadingValue<
firestore.QuerySnapshot,
Error
>();
const ref = useIsEqualRef(query, reset);
useEffect(
() => {
if (!ref.current) {
setValue(undefined);
return;
}
ref.current
.get(options ? options.getOptions : undefined)
.then(setValue)
.catch(setError);
},
[ref.current]
);
return [value, loading, error];
};
export const useCollectionDataOnce = <T>(
query?: firestore.Query | null,
options?: {
getOptions?: firestore.GetOptions;
idField?: string;
}
): CollectionDataOnceHook<T> => {
const idField = options ? options.idField : undefined;
const getOptions = options ? options.getOptions : undefined;
const [value, loading, error] = useCollectionOnce(query, { getOptions });
return [
(value
? value.docs.map(doc => snapshotToData(doc, idField))
: undefined) as T[],
loading,
error,
];
};