UNPKG

react-firehooks

Version:

Lightweight dependency-free collection of React hooks for Firebase

26 lines (25 loc) 1.53 kB
import { onValue } from "firebase/database"; import { useCallback } from "react"; import { useListen } from "../internal/useListen.js"; import { LoadingState } from "../internal/useLoadingValue.js"; import { defaultConverter, isQueryEqual } from "./internal.js"; /** * Returns and updates the DataSnapshot of the Realtime Database query * @template Value Type of the object value * @param query Realtime Database query * @param options Options to configure how the object is fetched * `converter`: Function to extract the desired data from the DataSnapshot. Similar to Firestore converters. Default: `snap.val()`. * `initialValue`: Value that is returned while the object is being fetched. * @returns User, loading state, and error * - value: Object value; `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 useObjectValue(query, options) { const { converter = defaultConverter, initialValue = LoadingState } = options !== null && options !== void 0 ? options : {}; const onChange = useCallback((stableQuery, next, error) => onValue(stableQuery, (snap) => next(converter(snap)), error), // TODO: add options as dependency // eslint-disable-next-line react-hooks/exhaustive-deps []); return useListen(query !== null && query !== void 0 ? query : undefined, onChange, isQueryEqual, initialValue); }