react-firehooks
Version:
Lightweight dependency-free collection of React hooks for Firebase
38 lines (37 loc) • 1.53 kB
JavaScript
import { getAggregateFromServer } from "firebase/firestore";
import { useGet } from "../internal/useGet.js";
import { isAggregateSpecEqual, isQueryEqual } from "./internal.js";
// eslint-disable-next-line jsdoc/require-param, jsdoc/require-returns
/**
* @internal
*/
async function getData({ query, aggregateSpec }) {
const snap = await getAggregateFromServer(query, aggregateSpec);
return snap.data();
}
// eslint-disable-next-line jsdoc/require-param, jsdoc/require-returns
/**
* @internal
*/
function isEqual(a, b) {
if (a === undefined && b === undefined) {
return true;
}
const areSameRef = a !== undefined &&
b !== undefined &&
isQueryEqual(a.query, b.query) &&
isAggregateSpecEqual(a.aggregateSpec, a.aggregateSpec);
return areSameRef;
}
/**
* Returns aggregate of a Firestore Query. Does not update the result once initially calculated.
* @param query Firestore query the aggregate is calculated for
* @param aggregateSpec Aggregate specification
* @returns Size of the result set, loading state, and error
* - value: Aggregate of the Firestore query; `undefined` if the aggregate is currently being calculated, or an error occurred
* - loading: `true` while calculating the aggregate; `false` if the aggregate was calculated successfully or an error occurred
* - error: `undefined` if no error occurred
*/
export function useAggregateFromServer(query, aggregateSpec) {
return useGet(query ? { query, aggregateSpec } : undefined, getData, isEqual);
}