UNPKG

react-firehooks

Version:

Lightweight dependency-free collection of React hooks for Firebase

29 lines (28 loc) 1.6 kB
import { onSnapshot, } from "firebase/firestore"; import { useCallback } from "react"; import { useListen } from "../internal/useListen.js"; import { LoadingState } from "../internal/useLoadingValue.js"; import { isDocRefEqual } from "./internal.js"; /** * Returns and updates a DocumentSnapshot of a Firestore DocumentReference * @template AppModelType Shape of the data after it was converted from firestore * @template DbModelType Shape of the data in firestore * @param reference Firestore DocumentReference that will be subscribed to * @param options Options to configure the subscription * @returns Document snapshot, loading state, and error * - value: DocumentSnapshot; `undefined` if document does not exist, is currently being fetched, or an error occurred * - loading: `true` while fetching the document; `false` if the document was fetched successfully or an error occurred * - error: `undefined` if no error occurred */ export function useDocument(reference, options) { const { snapshotListenOptions } = options !== null && options !== void 0 ? options : {}; const { includeMetadataChanges = false, source = "default" } = (snapshotListenOptions !== null && snapshotListenOptions !== void 0 ? snapshotListenOptions : {}); const onChange = useCallback((stableRef, next, error) => onSnapshot(stableRef, { includeMetadataChanges, source, }, { next, error, }), [includeMetadataChanges, source]); return useListen(reference !== null && reference !== void 0 ? reference : undefined, onChange, isDocRefEqual, LoadingState); }