import { useEffect } from 'react'; import { MedicationStatement } from 'fhir/r4'; import { useMedicationStatementServiceContext, useFhirServiceContext, usePatientServiceContext, useWebSocketServiceContext } from '../services'; export const useFhirMedicationStatementBroadcast = () => { const { subscribe, unsubscribe } = useWebSocketServiceContext(); const { medicationStatementsList, publishMedicationStatement } = useMedicationStatementServiceContext(); const { patientState } = usePatientServiceContext(); const { extractReferenceId } = useFhirServiceContext(); useEffect(() => { if (!patientState) { return; } const handleMedicationStatementEvent = (cloudEvent: any) => { const medicationStatement: MedicationStatement = cloudEvent.data; const eventType = cloudEvent.type; const patientId = extractReferenceId(medicationStatement.subject); // Through the service's floor, as its searches and save answers are: an older event never replaces a newer row. if (patientState.id === patientId) { if (eventType === 'com.akashichealthrecords.fhir.medicationstatement.created') publishMedicationStatement(medicationStatement, 'created'); else if (eventType === 'com.akashichealthrecords.fhir.medicationstatement.updated') publishMedicationStatement(medicationStatement, 'updated'); else if (eventType === 'com.akashichealthrecords.fhir.medicationstatement.deleted') publishMedicationStatement(medicationStatement, 'deleted'); } }; subscribe('com.akashichealthrecords.fhir.medicationstatement.created', handleMedicationStatementEvent); subscribe('com.akashichealthrecords.fhir.medicationstatement.updated', handleMedicationStatementEvent); subscribe('com.akashichealthrecords.fhir.medicationstatement.deleted', handleMedicationStatementEvent); return () => { unsubscribe('com.akashichealthrecords.fhir.medicationstatement.created', handleMedicationStatementEvent); unsubscribe('com.akashichealthrecords.fhir.medicationstatement.updated', handleMedicationStatementEvent); unsubscribe('com.akashichealthrecords.fhir.medicationstatement.deleted', handleMedicationStatementEvent); }; }, [patientState, subscribe, unsubscribe, extractReferenceId, medicationStatementsList, publishMedicationStatement]); };