import { useEffect, useRef, useState } from 'react'; import type { Patient } from 'fhir/r4'; import { usePatientServiceContext } from '../../../services/PatientService'; import { useOptionalActiveEncounterContext } from './ActiveEncounterContext'; import { openVisitPatientId } from './openVisitPatientId'; /** * The open visit's patient, read from the app-level active-encounter slot so leaving the overview * does not lose it. Undefined whenever no visit is open. */ export const useOpenVisitPatient = (): Patient | undefined => { const active = useOptionalActiveEncounterContext()?.active; const patientId = openVisitPatientId(active?.encounter); const { fetchPatient, patientState } = usePatientServiceContext(); const [patient, setPatient] = useState(); const token = useRef(0); const known = patientState?.id === patientId ? patientState : undefined; useEffect(() => { const mine = ++token.current; if (!patientId || known) { setPatient(undefined); return; } void fetchPatient(patientId) .then((record) => { if (mine === token.current) setPatient(record); }) .catch(() => { if (mine === token.current) setPatient(undefined); }); }, [patientId, known, fetchPatient]); // Identity gate at render: a record for any other id is never returned. if (!patientId) return undefined; if (known) return known; return patient?.id === patientId ? patient : undefined; };