import { useEffect, useState, useCallback } from 'react'; import { usePatientServiceContext, useDeviceServiceContext } from '../services'; import { describeFetchFailure } from '../utils/fetchFailureMessage'; interface UseFhirDevicesOptions { autoLoad?: boolean; errorMessage?: string; forceReload?: boolean; } interface UseFhirDevicesReturn { loading: boolean; error: string | undefined; loadDevices: () => Promise; clearError: () => void; /** This patient's read has answered, one way or the other. Until then an empty list is unknown. */ answered: boolean; /** The read could be asked at all: there is a patient to ask about. */ attempted: boolean; devicesBundle: ReturnType['devicesBundle']; devicesList: ReturnType['devicesList']; } export const useFhirDevices = (options: UseFhirDevicesOptions = {}): UseFhirDevicesReturn => { const { autoLoad = true, errorMessage = "Failed to load devices", forceReload = false } = options; const { patientState } = usePatientServiceContext(); const { cachedForPatientId, fetchDevicesWithPolling, devicesBundle, devicesList } = useDeviceServiceContext(); const [loading, setLoading] = useState(false); const [error, setError] = useState(); const loadDevices = useCallback(async () => { if (!patientState) { return; } setLoading(true); setError(undefined); try { await fetchDevicesWithPolling(patientState); } catch (err) { console.error('Failed to load devices:', err); setError(describeFetchFailure(err, errorMessage)); } finally { setLoading(false); } }, [patientState, fetchDevicesWithPolling, errorMessage]); const clearError = useCallback(() => { setError(undefined); }, []); useEffect(() => { if (!autoLoad) return; if (!patientState) return; // A bundle belonging to SOMEBODY ELSE is not a reason not to ask. This used to fire only when // there was no bundle at all, so moving between two charts left the previous patient's list in // place, with no request and nothing on screen to say it was not theirs. // NOT a refetch on every navigation: same patient, bundle loaded, no request. if (!devicesBundle || cachedForPatientId !== patientState.id || forceReload) { loadDevices(); } }, [autoLoad, patientState, devicesBundle, cachedForPatientId, forceReload, loadDevices]); return { loading, error, loadDevices, clearError, answered: Boolean(error) || (Boolean(devicesBundle) && cachedForPatientId === patientState?.id), attempted: Boolean(patientState), devicesBundle, devicesList }; };