import { useMemo } from 'react'; import { snapshotToData } from './helpers'; import type { FirebaseFirestoreTypes } from '@react-native-firebase/firestore'; import type { Data, DataOptions, DocumentDataHook, DocumentDataOnceHook, DocumentHook, DocumentOnceHook, OnceOptions, Options, OnceDataOptions, } from './types'; import { useInternalOnce } from './useInternalOnce'; import { useInternal } from './useInternal'; export const useDocument = ( docRef?: FirebaseFirestoreTypes.DocumentReference | null, optionsProp?: Options ): DocumentHook => useInternal>(docRef, optionsProp); export const useDocumentOnce = ( docRef?: FirebaseFirestoreTypes.DocumentReference | null, options?: Options & OnceOptions ) => useInternalOnce>(docRef, options); export const useDocumentData = < T = FirebaseFirestoreTypes.DocumentData, IDField extends string | undefined = undefined, RefField extends string | undefined = undefined >( docRef?: FirebaseFirestoreTypes.DocumentReference | null, options?: DataOptions ): DocumentDataHook => { const [snapshot, loading, error] = useDocument(docRef, options); const value = useGetValuesFromSnapshots(snapshot, options); return useMemo>( () => [value, loading, error], [value, loading, error] ); }; export const useDocumentDataOnce = < T = FirebaseFirestoreTypes.DocumentData, IDField extends string | undefined = undefined, RefField extends string | undefined = undefined >( docRef?: FirebaseFirestoreTypes.DocumentReference | null, options?: DataOptions & OnceDataOptions ) => { const [snapshot, loading, error] = useDocumentOnce(docRef, options); const values = useGetValuesFromSnapshots(snapshot, options); return useMemo>( () => [values, loading, error], [values, loading, error] ); }; const useGetValuesFromSnapshots = < T, IDField extends string | undefined = undefined, RefField extends string | undefined = undefined >( docRef?: FirebaseFirestoreTypes.DocumentSnapshot, options?: DataOptions & OnceDataOptions ) => { return useMemo( () => (docRef ? snapshotToData( docRef, options?.idField, options?.refField, options?.transform ) : undefined) as Data, [docRef, options?.idField, options?.refField, options?.transform] ); };