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