import { useEffect, useState } from 'react'; import { ownerOf, type OwnerRead } from './ownerReference'; type ReadOwner = (organizationId: string) => Promise<{ status: string; ownerPractitionerId?: string }>; /** The accepted owner of the practice on screen; undefined while unread, on a failed read, or for another practice. */ export const usePracticeOwner = (organizationId: string | undefined, readOwner: ReadOwner, skip = false): string | undefined => { const [read, setRead] = useState(); useEffect(() => { if (skip || !organizationId) return; let cancelled = false; readOwner(organizationId) .then((owner) => { if (!cancelled) setRead({ organizationId, practitionerId: owner.status === 'accepted' ? owner.ownerPractitionerId : undefined }); }) .catch(() => { if (!cancelled) setRead(undefined); }); return () => { cancelled = true; }; }, [organizationId, readOwner, skip]); return ownerOf(read, organizationId); };