-
Notifications
You must be signed in to change notification settings - Fork 0
/
useDocumentsData.ts
66 lines (59 loc) · 1.9 KB
/
useDocumentsData.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
56
57
58
59
60
61
62
63
64
65
66
import { onSnapshot } from 'firebase/firestore';
import { useState } from 'react';
import { useRefsEffect } from './useRefsEffect.js';
import type { FirebaseError } from 'firebase/app';
import type { DocumentReference, SnapshotOptions, Unsubscribe } from 'firebase/firestore';
export type UseDocumentsDataOptions = {
snapshotOptions?: SnapshotOptions;
throwError?: boolean;
};
export const useDocumentsData = <T>(
refs?: DocumentReference<T>[] | null,
{ snapshotOptions, throwError = true }: UseDocumentsDataOptions = {},
) => {
const [data, setData] = useState<(T | undefined)[]>([]);
const [loading, setLoading] = useState<boolean | undefined>();
const [errors, setErrors] = useState<FirebaseError[]>([]);
useRefsEffect(() => {
let isMounted = true;
if (!refs || refs.length === 0) {
setData([]);
return;
}
setLoading(true);
const unsubscribes: Unsubscribe[] = [];
const fetchDataPromises = refs.map((ref, index) => {
return new Promise<void>((resolve, reject) => {
const unsubscribe = onSnapshot(
ref,
(snapshot) => {
if (isMounted)
setData((prevData) => {
const newData = [...prevData];
newData[index] = snapshot.data(snapshotOptions);
return newData;
});
resolve();
},
(error) => {
if (throwError) reject(error);
if (isMounted) {
setErrors((prev) => [...prev, error]);
setLoading(false);
}
resolve();
},
);
unsubscribes.push(unsubscribe);
});
});
Promise.all(fetchDataPromises).finally(() => {
if (isMounted) setLoading(false);
});
return () => {
unsubscribes.forEach((unsubscribe) => unsubscribe());
isMounted = false;
};
}, refs || []);
return { data, loading, errors };
};