import { useEffect, useRef, useState } from 'react'; import { useOrgAuthorizationServiceContext, type OrgConsentStatusesResponse, } from '../../../services/OrgAuthorizationService.tsx'; export type ConsentStatusesByPatientId = Record; /** * All three agreements for each distinct patient on the board, from the same org-authorization read * check-in uses. One read per patient for the life of the board; a failed read is forgotten so the next * pass asks again rather than hiding the marker for good. */ export const useConsentStatusesByPatient = (patientIds: Array): ConsentStatusesByPatientId => { const { getConsentStatuses } = useOrgAuthorizationServiceContext(); const [statusesByPatientId, setStatusesByPatientId] = useState({}); const requestedRef = useRef>(new Set()); // Order- and duplicate-independent, so a same-set re-render does not re-run the effect. const idsKey = Array.from(new Set(patientIds.filter((id): id is string => Boolean(id)))).sort().join('|'); useEffect(() => { const ids = idsKey ? idsKey.split('|') : []; ids.forEach((patientId) => { if (requestedRef.current.has(patientId)) return; requestedRef.current.add(patientId); void getConsentStatuses(patientId) .then((statuses) => { setStatusesByPatientId((current) => ({ ...current, [patientId]: statuses })); }) .catch((error: unknown) => { console.error(`Failed to load the agreements for Patient/${patientId}:`, error); requestedRef.current.delete(patientId); }); }); }, [idsKey, getConsentStatuses]); return statusesByPatientId; };