-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseCollectionDataOnce.ts
45 lines (39 loc) · 1.33 KB
/
useCollectionDataOnce.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
import { getDocs } from 'firebase/firestore';
import { useState } from 'react';
import { useQueriesEffect } from './useQueriesEffect.js';
import type { FirebaseError } from 'firebase/app';
import type { Query, SnapshotOptions } from 'firebase/firestore';
export type UseCollectionDataOnceOptions = {
snapshotOptions?: SnapshotOptions;
throwError?: boolean;
};
export const useCollectionDataOnce = <T>(
query?: Query<T> | null,
{ snapshotOptions, throwError = true }: UseCollectionDataOnceOptions = {},
) => {
const [data, setData] = useState<T[]>([]);
const [loading, setLoading] = useState<boolean | undefined>();
const [error, setError] = useState<FirebaseError | undefined>();
useQueriesEffect(() => {
let isMounted = true;
if (!query) return;
setLoading(true);
getDocs(query)
.then((snapshot) => {
if (!isMounted) return;
setData(snapshot.docs.map((doc) => doc.data(snapshotOptions)));
setLoading(false);
})
.catch((error) => {
if (throwError) throw error;
if (!isMounted) return;
setError(error);
setLoading(false);
});
return () => {
isMounted = false;
};
// NOTE: Since a warning is displayed when the query is null, an empty object is being passed.
}, [query || ({} as Query<T>)]);
return { data, loading, error };
};