Skip to content

Commit ff56973

Browse files
committed
Add useCollectionData and useDocumentData
1 parent ed9884c commit ff56973

File tree

4 files changed

+61
-0
lines changed

4 files changed

+61
-0
lines changed

firestore/helpers/index.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import { firestore } from 'firebase';
2+
3+
export const snapshotToData = (
4+
snapshot: firestore.DocumentSnapshot,
5+
idField?: string
6+
) => ({
7+
...snapshot.data(),
8+
...(idField ? { [idField]: snapshot.id } : null),
9+
});

firestore/index.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,10 @@
11
export { default as useCollection, CollectionHook } from './useCollection';
2+
export {
3+
default as useCollectionData,
4+
CollectionDataHook,
5+
} from './useCollectionData';
26
export { default as useDocument, DocumentHook } from './useDocument';
7+
export {
8+
default as useDocumentData,
9+
DocumentDataHook,
10+
} from './useDocumentData';

firestore/useCollectionData.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import { firestore } from 'firebase';
2+
import useCollection from './useCollection';
3+
import { snapshotToData } from './helpers';
4+
5+
export type CollectionDataHook<T> = {
6+
error?: object;
7+
loading: boolean;
8+
value?: T[];
9+
};
10+
11+
export default <T>(
12+
query?: firestore.Query | null,
13+
idField?: string
14+
): CollectionDataHook<T> => {
15+
const { error, loading, value } = useCollection(query);
16+
return {
17+
error,
18+
loading,
19+
value: (value
20+
? value.docs.map(doc => snapshotToData(doc, idField))
21+
: undefined) as T[],
22+
};
23+
};

firestore/useDocumentData.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { firestore } from 'firebase';
2+
import useDocument from './useDocument';
3+
import { snapshotToData } from './helpers';
4+
5+
export type DocumentDataHook<T> = {
6+
error?: object;
7+
loading: boolean;
8+
value?: T;
9+
};
10+
11+
export default <T>(
12+
docRef?: firestore.DocumentReference | null,
13+
idField?: string
14+
): DocumentDataHook<T> => {
15+
const { error, loading, value } = useDocument(docRef);
16+
return {
17+
error,
18+
loading,
19+
value: (value ? snapshotToData(value, idField) : undefined) as T,
20+
};
21+
};

0 commit comments

Comments
 (0)