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