import { useEffect } from 'react'; import { Location } from 'fhir/r4'; import { useLocationServiceContext, useFhirServiceContext, useWebSocketServiceContext } from '../services'; export const useFhirLocationBroadcast = () => { const { subscribe, unsubscribe } = useWebSocketServiceContext(); const { locationsList, setLocationsList } = useLocationServiceContext(); const { extractReferenceId } = useFhirServiceContext(); useEffect(() => { const handleLocationEvent = (cloudEvent: any) => { const location: Location = cloudEvent.data; const eventType = cloudEvent.type; switch (eventType) { case 'com.akashichealthrecords.fhir.location.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. setLocationsList(prev => prev.some(p => p.id === location.id) ? prev.map(p => p.id === location.id ? location : p) : [...prev, location] ); break; case 'com.akashichealthrecords.fhir.location.updated': setLocationsList(prev => prev.map(p => p.id === location.id ? location : p)); break; case 'com.akashichealthrecords.fhir.location.deleted': setLocationsList(prev => prev.filter(p => p.id !== location.id)); break; } }; subscribe('com.akashichealthrecords.fhir.location.created', handleLocationEvent); subscribe('com.akashichealthrecords.fhir.location.updated', handleLocationEvent); subscribe('com.akashichealthrecords.fhir.location.deleted', handleLocationEvent); return () => { unsubscribe('com.akashichealthrecords.fhir.location.created', handleLocationEvent); unsubscribe('com.akashichealthrecords.fhir.location.updated', handleLocationEvent); unsubscribe('com.akashichealthrecords.fhir.location.deleted', handleLocationEvent); }; }, [subscribe, unsubscribe, extractReferenceId, locationsList]); };