import { useEffect } from 'react'; import { AdverseEvent } from 'fhir/r4'; import { useAdverseEventServiceContext, useFhirServiceContext, usePatientServiceContext, useWebSocketServiceContext } from '../services'; import { isArchived } from '../utils/archivedResource'; export const useFhirAdverseEventBroadcast = () => { const { subscribe, unsubscribe } = useWebSocketServiceContext(); const { adverseEventsList, setAdverseEventsList } = useAdverseEventServiceContext(); const { patientState } = usePatientServiceContext(); const { extractReferenceId } = useFhirServiceContext(); useEffect(() => { if (!patientState) { return; } const handleAdverseEventEvent = (cloudEvent: any) => { const adverseEvent: AdverseEvent = cloudEvent.data; const eventType = cloudEvent.type; const patientId = extractReferenceId(adverseEvent.subject); if (patientState.id === patientId) { switch (eventType) { case 'com.akashichealthrecords.fhir.adverseevent.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. setAdverseEventsList(prev => prev.some(p => p.id === adverseEvent.id) ? prev.map(p => p.id === adverseEvent.id ? adverseEvent : p) : [...prev, adverseEvent] ); break; case 'com.akashichealthrecords.fhir.adverseevent.updated': setAdverseEventsList(prev => isArchived(adverseEvent) ? prev.filter(p => p.id !== adverseEvent.id) : prev.map(p => p.id === adverseEvent.id ? adverseEvent : p) ); break; case 'com.akashichealthrecords.fhir.adverseevent.deleted': setAdverseEventsList(prev => prev.filter(p => p.id !== adverseEvent.id)); break; } } }; subscribe('com.akashichealthrecords.fhir.adverseevent.created', handleAdverseEventEvent); subscribe('com.akashichealthrecords.fhir.adverseevent.updated', handleAdverseEventEvent); subscribe('com.akashichealthrecords.fhir.adverseevent.deleted', handleAdverseEventEvent); return () => { unsubscribe('com.akashichealthrecords.fhir.adverseevent.created', handleAdverseEventEvent); unsubscribe('com.akashichealthrecords.fhir.adverseevent.updated', handleAdverseEventEvent); unsubscribe('com.akashichealthrecords.fhir.adverseevent.deleted', handleAdverseEventEvent); }; }, [patientState, subscribe, unsubscribe, extractReferenceId, adverseEventsList]); };