import { useEffect } from 'react'; import { DeviceRequest } from 'fhir/r4'; import { useDeviceRequestServiceContext, useFhirServiceContext, usePatientServiceContext, useWebSocketServiceContext } from '../services'; import { isArchived } from '../utils/archivedResource'; export const useFhirDeviceRequestBroadcast = () => { const { subscribe, unsubscribe } = useWebSocketServiceContext(); const { deviceRequestsList, setDeviceRequestsList } = useDeviceRequestServiceContext(); const { patientState } = usePatientServiceContext(); const { extractReferenceId } = useFhirServiceContext(); useEffect(() => { if (!patientState) { return; } const handleDeviceRequestEvent = (cloudEvent: any) => { const deviceRequest: DeviceRequest = cloudEvent.data; const eventType = cloudEvent.type; const patientId = extractReferenceId(deviceRequest.subject); if (patientState.id === patientId) { switch (eventType) { case 'com.akashichealthrecords.fhir.devicerequest.created': // The list has two writers: this broadcast, and the service's own refetch after a write // (several of which POLL until the new id appears). Refetch first and the list already holds // the record, so an unconditional append put a SECOND copy of it on screen - observed on a // patient's questionnaire answers, where one submission rendered as two completed forms. // Keeping the broadcast's copy rather than skipping: its body is at least as fresh. setDeviceRequestsList(prev => prev.some(p => p.id === deviceRequest.id) ? prev.map(p => p.id === deviceRequest.id ? deviceRequest : p) : [...prev, deviceRequest] ); break; case 'com.akashichealthrecords.fhir.devicerequest.updated': setDeviceRequestsList(prev => isArchived(deviceRequest) ? prev.filter(p => p.id !== deviceRequest.id) : prev.map(p => p.id === deviceRequest.id ? deviceRequest : p) ); break; case 'com.akashichealthrecords.fhir.devicerequest.deleted': setDeviceRequestsList(prev => prev.filter(p => p.id !== deviceRequest.id)); break; } } }; subscribe('com.akashichealthrecords.fhir.devicerequest.created', handleDeviceRequestEvent); subscribe('com.akashichealthrecords.fhir.devicerequest.updated', handleDeviceRequestEvent); subscribe('com.akashichealthrecords.fhir.devicerequest.deleted', handleDeviceRequestEvent); return () => { unsubscribe('com.akashichealthrecords.fhir.devicerequest.created', handleDeviceRequestEvent); unsubscribe('com.akashichealthrecords.fhir.devicerequest.updated', handleDeviceRequestEvent); unsubscribe('com.akashichealthrecords.fhir.devicerequest.deleted', handleDeviceRequestEvent); }; }, [patientState, subscribe, unsubscribe, extractReferenceId, deviceRequestsList]); };