import { useEffect } from 'react'; import { VisionPrescription } from 'fhir/r4'; import { useVisionPrescriptionServiceContext, useFhirServiceContext, usePatientServiceContext, useWebSocketServiceContext } from '../services'; import { isArchived } from '../utils/archivedResource'; export const useFhirVisionPrescriptionBroadcast = () => { const { subscribe, unsubscribe } = useWebSocketServiceContext(); const { visionPrescriptionsList, setVisionPrescriptionsList } = useVisionPrescriptionServiceContext(); const { patientState } = usePatientServiceContext(); const { extractReferenceId } = useFhirServiceContext(); useEffect(() => { if (!patientState) { return; } const handleVisionPrescriptionEvent = (cloudEvent: any) => { const visionPrescription: VisionPrescription = cloudEvent.data; const eventType = cloudEvent.type; const patientId = extractReferenceId(visionPrescription.patient); if (patientState.id === patientId) { switch (eventType) { case 'com.akashichealthrecords.fhir.visionprescription.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. setVisionPrescriptionsList(prev => prev.some(p => p.id === visionPrescription.id) ? prev.map(p => p.id === visionPrescription.id ? visionPrescription : p) : [...prev, visionPrescription] ); break; case 'com.akashichealthrecords.fhir.visionprescription.updated': setVisionPrescriptionsList(prev => isArchived(visionPrescription) ? prev.filter(p => p.id !== visionPrescription.id) : prev.map(p => p.id === visionPrescription.id ? visionPrescription : p) ); break; case 'com.akashichealthrecords.fhir.visionprescription.deleted': setVisionPrescriptionsList(prev => prev.filter(p => p.id !== visionPrescription.id)); break; } } }; subscribe('com.akashichealthrecords.fhir.visionprescription.created', handleVisionPrescriptionEvent); subscribe('com.akashichealthrecords.fhir.visionprescription.updated', handleVisionPrescriptionEvent); subscribe('com.akashichealthrecords.fhir.visionprescription.deleted', handleVisionPrescriptionEvent); return () => { unsubscribe('com.akashichealthrecords.fhir.visionprescription.created', handleVisionPrescriptionEvent); unsubscribe('com.akashichealthrecords.fhir.visionprescription.updated', handleVisionPrescriptionEvent); unsubscribe('com.akashichealthrecords.fhir.visionprescription.deleted', handleVisionPrescriptionEvent); }; }, [patientState, subscribe, unsubscribe, extractReferenceId, visionPrescriptionsList]); };