import { RaRecord, Identifier } from '../types'; import { UseGetManyHookValue, useGetManyAggregate } from '../dataProvider'; import { UseQueryOptions } from 'react-query'; interface UseReferenceProps { id: Identifier; reference: string; options?: UseQueryOptions; } export interface UseReferenceResult { isLoading: boolean; isFetching: boolean; referenceRecord?: RecordType; error?: any; refetch: UseGetManyHookValue['refetch']; } /** * @typedef UseReferenceResult * @type {Object} * @property {boolean} isFetching: boolean indicating if the reference is loading * @property {boolean} isLoading: boolean indicating if the reference has loaded at least once * @property {Object} referenceRecord: the referenced record. */ /** * Fetch reference record, and return it when available * * The reference prop should be the name of one of the components * added as child. * * @example * * const { isLoading, referenceRecord } = useReference({ * id: 7, * reference: 'users', * }); * * @param {Object} option * @param {string} option.reference The linked resource name * @param {string} option.id The id of the reference * * @returns {UseReferenceResult} The reference record */ export const useReference = ({ reference, id, options = {}, }: UseReferenceProps): UseReferenceResult => { const { meta, ...otherQueryOptions } = options; const { data, error, isLoading, isFetching, refetch } = useGetManyAggregate< RecordType >(reference, { ids: [id], meta }, otherQueryOptions); return { referenceRecord: error ? undefined : data ? data[0] : undefined, refetch, error, isLoading, isFetching, }; };