react-firehooks
Version:
Lightweight dependency-free collection of React hooks for Firebase
29 lines (28 loc) • 1.51 kB
JavaScript
import { onSnapshot } from "firebase/firestore";
import { useCallback } from "react";
import { useListen } from "../internal/useListen.js";
import { LoadingState } from "../internal/useLoadingValue.js";
import { isQueryEqual } from "./internal.js";
/**
* Returns and updates a QuerySnapshot of a Firestore Query
* @template AppModelType Shape of the data after it was converted from firestore
* @template DbModelType Shape of the data in firestore
* @param query Firestore query that will be subscribed to
* @param options Options to configure the subscription
* @returns QuerySnapshot, loading, and error
* - value: QuerySnapshot; `undefined` if query is currently being fetched, or an error occurred
* - loading: `true` while fetching the query; `false` if the query was fetched successfully or an error occurred
* - error: `undefined` if no error occurred
*/
export function useQuery(query, options) {
const { snapshotListenOptions } = options !== null && options !== void 0 ? options : {};
const { includeMetadataChanges = false, source = "default" } = (snapshotListenOptions !== null && snapshotListenOptions !== void 0 ? snapshotListenOptions : {});
const onChange = useCallback((stableQuery, next, error) => onSnapshot(stableQuery, {
includeMetadataChanges,
source,
}, {
next,
error,
}), [includeMetadataChanges, source]);
return useListen(query !== null && query !== void 0 ? query : undefined, onChange, isQueryEqual, LoadingState);
}