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